@FeignClient用于Nacos微服务间的接口调用

复制代码
依赖:
java 复制代码
<!-- spring-boot启动依赖 -->
<!-- 提供者 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- openFeign -->
<!-- 消费者-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

yml配置

java 复制代码
feign:
  compression:
    response:
      enabled: true
    request:
      enabled: true
      mime-types: text/xml,application/xml,application/json
      min-request-size: 2048
  circuitbreaker:
    enabled: true
  client:
    config:
      default:
        connectTimeout: 5000
        readTimeout: 5000
        loggerLevel: basic

提供者创建RESTful接口,controller接口 @RestController @GetMapping("/url")

消费者创建feign目录,创建Interface ManagementClient

java 复制代码
//name 填写
//spring:
//application:
//  name: management
//springboot的服务名
//fallback填写实现类,用于接口回调,接口异常时返回保底数据
@FeignClient(name = "management", fallback = ManagementClientFallback.class)
public interface ManagementClient {

    @PostMapping("/url")
    OperaResponse selectList(@RequestBody IdRequest request);
}

/feign/impl,创建ManagementClientFallback类

java 复制代码
/**
 * fallback是在远程服务调用失败时,向调用方返回一个备用(回退)响应的机制
 */
@Component
public class ManagementClientFallback implements ManagementClient {
    @Override
    public OperaResponse selectList(IdRequest request) {
        return OperaResponse.error(ErrStatus.FEIGN_ERROR);
    }
}

创建ClientUtil用于调用Client方法,service层依赖注入Client,将Client对象和参数传给ClientUtil方法

java 复制代码
    @Autowired
    private ChannelManagementClient channelManagementClient;
java 复制代码
public class ClientUtil {
    private ClientUtil(){
    }

    public static List<Response> selectList(ManagementClient client, Integer Id){
        IdRequest request = new IdRequest();
        request.setId(id);
        OperaResponse operaResponse = client.selectList(request);
        if(operaResponse.getData() == null){
            return new ArrayList<>();
        }
        List<Response> list = JSONObject.parseArray(JSONObject.toJSONString(operaResponse.getData()), Response.class);
        return list == null ? new ArrayList<>() : list;
    }
}
相关推荐
武子康12 分钟前
Java-71 深入浅出 RPC Dubbo 上手 父工程配置编写 附详细POM与代码
java·分布式·程序人生·spring·微服务·rpc·dubbo
武子康2 小时前
Java-72 深入浅出 RPC Dubbo 上手 生产者模块详解
java·spring boot·分布式·后端·rpc·dubbo·nio
_殊途3 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
椰椰椰耶4 小时前
【Spring】拦截器详解
java·后端·spring
没有bug.的程序员5 小时前
JAVA面试宝典 - 《MyBatis 进阶:插件开发与二级缓存》
java·面试·mybatis
saynaihe5 小时前
ubuntu 22.04 anaconda comfyui安装
linux·运维·服务器·ubuntu
小蜜蜂爱编程6 小时前
ubuntu透网方案
运维·服务器·ubuntu
没有羊的王K6 小时前
SSM框架学习——day1
java·学习
又菜又爱coding6 小时前
安装Keycloak并启动服务(macOS)
java·keycloak
不知道叫什么呀7 小时前
【C】vector和array的区别
java·c语言·开发语言·aigc