@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;
    }
}
相关推荐
Flash.kkl15 分钟前
Linux——进程信号
运维·服务器
码出财富1 小时前
SpringBoot 内置的 20 个高效工具类
java·spring boot·spring cloud·java-ee
苏宸啊1 小时前
Linux权限
linux·运维·服务器
我是小疯子662 小时前
Python变量赋值陷阱:浅拷贝VS深拷贝
java·服务器·数据库
森叶2 小时前
Java 比 Python 高性能的原因:重点在高并发方面
java·开发语言·python
xqhoj2 小时前
Linux——make、makefile
linux·运维·服务器
二哈喇子!2 小时前
Eclipse中导入外部jar包
java·eclipse·jar
微露清风2 小时前
系统性学习C++-第二十二讲-C++11
java·c++·学习
lifejump3 小时前
Pikachu | XXE
服务器·web安全·网络安全·安全性测试
进阶小白猿3 小时前
Java技术八股学习Day20
java·开发语言·学习