java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > OpenFeign动态URl、动态传递接口

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

作者: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);

}

说明:

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

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、动态传递接口内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文