OpenFeign中动态URl、动态传递接口地址

2023-11-08

前言:
在微服务盛行的今天,做接口开发请求第三方服务的接口,大概率会用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动态配置,请求路径也可实现动态,
如果有其它方式还请留言多交流;

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

OpenFeign中动态URl、动态传递接口地址 的相关文章

随机推荐

  • 解决sqlplus /as sysdba登陆oracle无效

    安装完oracle 然后执行完下面的自动配置脚本后 没有任何地方设置过密码 etc init d oracledb ORCLCDB 19c configure 在这个命令执行完成后 会提醒查看完整日志的地方 Look at the log
  • C语言100例 第一天习题练习

    C语言中基本的输入与输出 例题1 输入两个正整数a和b 输出a b的值 其中a b 10000 include
  • Centos7 开机卡死在桌面

    问题 Centos7 开机死卡成了这样 一动不动 如下图 原因 一般来说是一些开机自启的东西使得Centos卡死 有可能是在 etc rc d rc local文件里加入的脚本 也有可能 etc fstab文件里面自动挂载的硬盘 解决方法
  • 【自然语言处理】情感分析(三):基于 Word2Vec 的 LSTM 实现

    情感分析 三 基于 Word2Vec 的 LSTM 实现 本文是 情感分析 系列的第 3 3 3 篇 前两篇分别是 自然语言处理 情感分析 一 基于 NLTK 的 Naive Bayes 实现 自然语言处理 情感分析 二 基于 scikit
  • jmeter调试错误大全

    一 前言 在使用jmeter做接口测试的过程中大家是不是经常会遇到很多问题 但是无从下手 不知道从哪里开始找起 对于初学者而言这是一个非常头痛的事情 这里结合笔者的经验 总结出以下方法 二 通过查看运行日志调试问题 写好脚本后 可以先试着运
  • 【保姆级】Python最新版3.11.1开发环境搭建,看这一篇就够了(适用于Python3.11.2安装)

    工欲善其事必先利其器 在使用Python开发程序之前 在计算机上搭建Python开发环境是必不可少的环节 目前Python最新稳定版本是3 11 1 且支持到2027年 如下图所示 本文手把手带你从0 到1搭建Python最新版3 11 1
  • 如何在Mac上远程控制另一台Mac

    1 先请在苹果 Mac 电脑上的 系统偏好设置 窗口中打开 共享 功能 2 接着在共享窗口中的左侧点击启用 屏幕共享 选项 3 当屏幕共享功能打开以后 请点击 电脑设置 按钮 4 随后请勾选二个选项 VNC 显示程序可以使用密码控制屏幕 并
  • 异步赠书:9月重磅新书升级,本本经典

    本期活动已结束 新活动地址 http blog csdn net epubit17 article details 78210459 获奖读者名单 如下 领取赠书步骤 1 加入异步社区活动QQ群439467328 2 在下方地址中填写收件信
  • java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.isAsyncStarted()Z 的解决

    jetty 9 嵌入式开发时 启动正常 但是页面一浏览就报错如下 java lang NoSuchMethodError javax servlet http HttpServletRequest isAsyncStarted Z 原因 j
  • 用i18n 实现vue2+element UI的国际化多语言切换详细步骤及代码

    一 i18n的安装 这个地方要注意自己的vue版本和i1n8的匹配程度 如果是vue2点几 记得安装i18n的 8版本 不然会自动安装的最新版本 后面会报错哦 查询了下资料 好像最新版本是适配的vue3 npm install vue i1
  • angular请求的防抖(debounce)

    在开发项目过程中 我们会遇到这样的场景 当用户在搜索框中输入名字时 当用户输入完毕后 自动发送搜索请求 实时响应 而不是多按一个按钮或者回车键 如果按照常规思路 我们会绑定input的keyup事件 每次击键后 执行相对应的请求函数 但是
  • MyBatis 3 提示 Column ‘******‘ specified twice

    造成错误的原因是 Mapper xml 配置文件 insert 语句写入重复字段 错误配置文件展示
  • 如何进行本地分支管理

    文章目录 如何进行本地分支管理 Git进行分支管理 显示分支一览表 创建分支 转到新创建的分支 创建分支并转到新创建的分支 分支合并 删除分支 冲突合并 Tortoise进行分支管理 显示分支 创建分支 切换分支 分支合并 冲突合并 VS2
  • 绕过__chkesp堆栈检查

    前面很多注入相关的文章中都提到为了保证注入后原始程序能恢复正常的执行流 需要在编译器中关闭堆栈检查 为了解决问题 这是个好手段 但是不得不说这是回避问题 不是根本上解决问题 本文旨在解决这个问题 vs用 chkesp来实现堆栈检查 chke
  • 工业制造业亟需数字化转型,区块链可以发挥哪些价值?

    智能信息化技术驱动的第四次工业革命正推动制造业积极拥抱物联网 云计算等新技术进行数字化 智能化转型升级 制造业是一个纷繁复杂的庞大网络 不仅涉及机器 零件 产品等实体还有机器制造商 物流公司 销售等诸多利益相关方 在当今数字化时代中 如何帮
  • 如何防止小人对你的网站进行反向代理

    引言 如果是小站或者刚建立的站 则不用担心 但如果有名气了 便可能出现小人反代你的网站 做成所谓的 镜像站点 盗版站点 这篇文章就是介绍如何防止一些简单的反代小人 实施方法 一 使用 htaccess禁止反向代理 在站点根目录下新建 hta
  • android根据物理按键上下选中listview的item,回车进入点击相应事件

    最近做扫码枪程序 因应用于冷库 用户需求在列表选择上可以用上下键代替滑动 所以做了一个小demo 记录一下 话不多说 直接上代码 1 布局文件很简单 主界面 一个输入框一个列表 因为是手持采集枪 输入框经常用到 所以在做demo的时候也加上
  • Mac终端(Terminal)自定义颜色,字体,背景 & Mac系统如何显示隐藏文件?& mac下载gcc并测试

    Mac终端 Terminal 自定义颜色 字体 背景 1 打开终端 输入 git clone git github com altercation solarized git下载Solarized 2 clone完成后 打开 然后打开 3
  • 矩阵乘法复杂度分析

    一 背景 在很多机器学习或者数据挖掘论文中 里面或多或少的涉及到算法复杂度分析 进一步思考 是如何得到的呢 很长时间里 我也感受到比较疑惑 阅读论文过程中 在涉及到这部分内容时 会直接跳过算法复杂度分析这快 其一是因为比较烧脑 虽然知道复杂
  • OpenFeign中动态URl、动态传递接口地址

    前言 在微服务盛行的今天 做接口开发请求第三方服务的接口 大概率会用feign做请求 而feign也是最常用的一种rpc框架 这里主要是说明在进行feign请求的时候 第三方服务的url和接口如何动态获取 若是该接口是作为基础服务可能会请求