Spring cloud OpenFeign中动态URl、动态传递接口地址代码示例

 更新时间:2024年02月04日 10:41:25   作者:Best_Liu~  
openFeign是作为微服务之间调用的解决方案,每个微服务项目是必不可少的,下面这篇文章主要给大家介绍了关于Spring cloud OpenFeign中动态URl、动态传递接口地址的相关资料,需要的朋友可以参考下

前言:

在微服务盛行的今天,做接口开发请求第三方服务的接口,大概率会用feign做请求,而feign也是最常用的一种rpc框架;

这里主要是说明在进行feign请求的时候,第三方服务的url和接口如何动态获取。

若是该接口是作为基础服务可能会请求多个第三方使用(我们就是不同分支的代码作为独立项目部署,请求不同的客户接口),不同客户的接口地址可能不同,此时就需要做成动态方式;

若是不常改动,其实也没必要动态了;

常用方式:

通常我们是这么请求第三方接口的:(用feign方式)

import com.zkaw.lxjtest.Dto.User;
import com.zkaw.lxjtest.remoteCall.feign.factory.RemoteFeignFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
 * @Author: Best_Liu
 * @Description:
 * @Date Create in 11:14 2022/7/1
 * @Modified By:
 */
@FeignClient(value = "mybatisPlus", url = "http://127.0.0.1:8090", fallbackFactory = RemoteFeignFactory.class)
public interface RemoteFeignClient {

    @PostMapping("/user/selectListNoPage")
    /*@Headers({"content-type:application/json"})*/
    List<User> test(@RequestBody User user);

}

说明:

  • 请求客户的url是:http://127.0.0.1:8090,
  • 调用客户的具体的目标方法是:/user/selectListNoPage 这个方法

第二种方式:配置文件传参

import com.zkaw.lxjtest.Dto.User;
import com.zkaw.lxjtest.remoteCall.feign.factory.RemoteFeignFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
 * @Author: Best_Liu
 * @Description:
 * @Date Create in 11:14 2022/7/1
 * @Modified By:
 */
@FeignClient(value = "mybatisPlus", url = "${feign.client.url.TestUrl}", fallbackFactory = RemoteFeignFactory.class)
public interface RemoteFeignClient {

    @PostMapping("/user/selectListNoPage")
    /*@Headers({"content-type:application/json"})*/
    List<User> test(@RequestBody User user);

}

然后添加配置文件,比如

在你的 application-dev.yml 文件中

feign:
  client:
    url:
      TestUrl: http://127.0.0.1:8088

第三种方式:调用feign时动态传入

实现了url和目标方法的动态传入

1、目标方法的动态传入

利用@PathVariable注解的特性;

用于接收请求路径中占位符的值

@PathVariable(“xxx”)
通过 @PathVariable 可以将URL中占位符参数{xxx}绑定到处理器类的方法形参中
如:
@RequestMapping(value=”user/{id}/{name}”)
请求路径:http://localhost:8080/hello/show/1/lisi

2、url动态实现

在创建feignclient时设置url地址

所以改造下我们的方法:

import com.zkaw.lxjtest.Dto.User;
import com.zkaw.lxjtest.remoteCall.feign.factory.RemoteFeignFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
 * @Author: Best_Liu
 * @Description:
 * @Date Create in 11:14 2022/7/1
 * @Modified By:
 */
@FeignClient(value = "mybatisPlus", fallbackFactory = RemoteFeignFactory.class)
public interface RemoteFeignClient {

    @PostMapping("{apiName}")
    /*@Headers({"content-type:application/json"})*/
    List<User> test(@PathVariable("apiName") String apiName, @RequestBody User user);

}

feign接口调用方式,createFeignClient是Feign核心部分

import com.zkaw.lxjtest.Dto.User;
import com.zkaw.lxjtest.remoteCall.feign.service.RemoteFeignClient;
import feign.Feign;
import feign.form.spring.SpringFormEncoder;
import feign.optionals.OptionalDecoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.cloud.openfeign.support.SpringMvcContract;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author: Best_Liu
 * @Description:
 * @Date Create in 11:20 2022/7/1
 * @Modified By:
 */
@RestController
@RequestMapping("/feign")
public class feignController {

    @Autowired
    ObjectFactory<HttpMessageConverters> messageConverters;

    private RemoteFeignClient createFeignClient(String url) {
        /*1、在创建Feign客户端的时候最核心的对象是decoder、encoder、contract
        通过跟踪源码与SpringBoot自动创建的Feign对象比较,设置decoder、encoder、
        contract为SpringBoot中自动创建对象相同,然后定义Feign接口的时候,
        各种参数的注解和方法的注解就可以和不动态修改url的相同了
        decoder解码器,对返回的结果进行解码*/
        OptionalDecoder decoder = new OptionalDecoder(new ResponseEntityDecoder(new SpringDecoder(messageConverters)));
        //encoder编码器,对输入的数据进行编码
        SpringEncoder springEncoder = new SpringEncoder(messageConverters);
        SpringFormEncoder encoder = new SpringFormEncoder(springEncoder);
        //该对象是将接口进行解析,方便生成最后调用的网络对象HttpurlConnection
        SpringMvcContract contract = new SpringMvcContract();
        RemoteFeignClient feignClient = Feign.builder()
                .decoder(decoder)
                .encoder(encoder)
                .contract(contract)
                //这个地方的Url可以根据每次调用的时候进行改变
                .target(RemoteFeignClient.class, url);
        return feignClient;
    }

    @PostMapping("/selectListNoPage")
    public List<User> selectListNoPage(@RequestBody User user){
        String apiName = "user/selectListNoPage";
        String url = "http://127.0.0.1:8090";
        RemoteFeignClient remoteFeignClient = createFeignClient(url);
        List<User> users = remoteFeignClient.test(apiName,user);
        return users;
    }
}

结果示例

 fallback方式服务降级

import com.zkaw.lxjtest.Dto.User;
import com.zkaw.lxjtest.remoteCall.feign.service.RemoteFeignClient;
import feign.hystrix.FallbackFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Best_Liu
 * @Description: 服务降级
 * @Date Create in 11:34 2022/7/1
 * @Modified By:
 */
@Component
public class RemoteFeignFactory implements FallbackFactory<RemoteFeignClient> {
    private static final Logger log = LoggerFactory.getLogger(RemoteFeignFactory.class);
    @Override
    public RemoteFeignClient create(Throwable throwable) {
        log.error("服务调用失败:{}", throwable.getMessage());
        return new RemoteFeignClient() {
            @Override
            public List<User> test(@PathVariable("apiName") String apiName, User user) {
                return new ArrayList<>();
            }
        };
    }
}

目前我想到的是这种方式,既可以把url动态配置,请求路径也可实现动态,

总结

到此这篇关于Spring cloud OpenFeign中动态URl、动态传递接口地址的文章就介绍到这了,更多相关OpenFeign动态URl、动态传递接口内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 利用Java读取Word表格中文本和图片的方法实例

    利用Java读取Word表格中文本和图片的方法实例

    这篇文章主要给大家介绍了关于如何利用Java读取Word表格中文本和图片的相关资料,主要利用的是free spire.doc.jar 包,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2021-07-07
  • Java实现图片切割功能

    Java实现图片切割功能

    这篇文章主要为大家详细介绍了Java实现图片切割功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • 求最大子数组之和的方法解析(2种可选)

    求最大子数组之和的方法解析(2种可选)

    本文主要对求最大子数组之和的方法进行详细解析,列了两种方法供大家选择借鉴,需要的朋友一起来看下吧
    2016-12-12
  • SpringBoot项目中新增脱敏功能的实例代码

    SpringBoot项目中新增脱敏功能的实例代码

    项目中,由于使用端有两个,对于两个端的数据权限并不一样。Web端可以查看所有数据,小程序端只能查看脱敏后的数据,这篇文章主要介绍了SpringBoot项目中新增脱敏功能,需要的朋友可以参考下
    2022-11-11
  • springboot 整合canal实现示例解析

    springboot 整合canal实现示例解析

    这篇文章主要为大家介绍了springboot整合canal的示例实现解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多多进步,早日升职加薪
    2022-02-02
  • java设计模式之装饰模式详细介绍

    java设计模式之装饰模式详细介绍

    这篇文章主要介绍了java设计模式之装饰模式,有需要的朋友可以参考一下
    2013-12-12
  • maven资源过滤打包后文件变大的处理方法

    maven资源过滤打包后文件变大的处理方法

    maven目前在web上面的使用方式很普遍,而打包的方式也存在很多方式,下面这篇文章主要给大家介绍了关于maven资源过滤打包后文件变大的处理方法,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2018-07-07
  • 深入解析Java中的数据类型与变量

    深入解析Java中的数据类型与变量

    这篇文章主要介绍了深入解析Java中的数据类型与变量,是Java入门学习中的基础知识,需要的朋友可以参考下
    2015-09-09
  • javacv视频抽帧的实现过程详解(附代码)

    javacv视频抽帧的实现过程详解(附代码)

    这篇文章主要介绍了javacv视频抽帧的实现过程详解(附代码),视频抽帧可以做一些处理,比如水印,去水印等操作,然后再合成视频,需要的朋友可以参考下
    2019-07-07
  • 在SpringBoot中整合使用Netty框架的详细教程

    在SpringBoot中整合使用Netty框架的详细教程

    这篇文章主要介绍了在SpringBoot中整合使用Netty框架的教程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-06-06

最新评论