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 线性表接口的实例详解

    java 线性表接口的实例详解

    这篇文章主要介绍了java 线性表接口的实现实例详解的相关资料,希望通过本能帮助到大家,需要的朋友可以参考下
    2017-09-09
  • 基于java使用钉钉机器人向钉钉群推送消息

    基于java使用钉钉机器人向钉钉群推送消息

    这篇文章主要介绍了基于java使用钉钉机器人向钉钉群推送消息,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • Java8新特性Stream短路终端操作实例解析

    Java8新特性Stream短路终端操作实例解析

    这篇文章主要介绍了Java8新特性Stream短路终端操作实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • java多线程读写文件示例

    java多线程读写文件示例

    这篇文章主要介绍了java多线程读写文件示例,需要的朋友可以参考下
    2014-04-04
  • Java实战角色权限后台脚手架系统的实现流程

    Java实战角色权限后台脚手架系统的实现流程

    只学书上的理论是远远不够的,只有在实战中才能获得能力的提升,本篇文章手把手带你用java+Springboot+Maven+myBaits-Plus+Vue+Element-UI+Mysql实现一个角色权限后台脚手架系统,大家可以在过程中查缺补漏,提升水平
    2022-01-01
  • MybatisPlus创建时间不想用默认值的问题

    MybatisPlus创建时间不想用默认值的问题

    MybatisPlus通过FieldFill注解和MpMetaObjectHandler类支持自动填充字段功能,特别地,可以设置字段在插入或更新时自动填充创建时间和更新时间,但在特定场景下,如导入数据时,可能需要自定义创建时间
    2024-09-09
  • MybatisPlus如何调用count函数

    MybatisPlus如何调用count函数

    这篇文章主要介绍了MybatisPlus如何调用count函数问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • Spring Boot整合邮件发送与注意事项

    Spring Boot整合邮件发送与注意事项

    这篇文章主要给大家介绍了关于Spring Boot整合邮件发送与注意事项的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-07-07
  • 深入了解Java设计模式之策略模式

    深入了解Java设计模式之策略模式

    策略模式属于Java-设计模式中行为模式之一,该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换。本文将通过示例详细讲解这一模式,需要的可以参考一下
    2022-09-09
  • 使用@Transactional 设置嵌套事务不回滚

    使用@Transactional 设置嵌套事务不回滚

    这篇文章主要介绍了使用@Transactional 设置嵌套事务不回滚问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07

最新评论