@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;
    }
}
相关推荐
云烟成雨TD2 分钟前
Spring AI Alibaba 1.x 系列【40】多智能体核心模式 - 智能体作为工具(Agent as Tool)
java·人工智能·spring
测试员周周14 分钟前
【踩坑系列3】飞书机器人集体“失联“?3 个 Gateway 进程让我差点崩溃!一个测试老兵的排查实录
java·python
aq553560015 分钟前
Laravel9.x新特性全解析
java·开发语言·数据库
亦暖筑序19 分钟前
AI 客服系统升级实战:多 Agent 路由 + 多轮记忆 + 敏感词过滤
java·后端
zhangzeyuaaa27 分钟前
深入理解 Python GIL:从机制到释放时机
java·网络·python
姚青&28 分钟前
Linux 文件处理命令
linux·运维·服务器
枷锁—sha33 分钟前
【CTFshow-pwn系列】03_栈溢出【pwn 072】详解:无字符串环境下的多级 Ret2Syscall 与 BSS 段注入
服务器·网络·汇编·笔记·安全·网络安全
zjeweler1 小时前
阿里云服务器利用宝塔搭建个人博客网站
服务器·阿里云·云计算
河阿里1 小时前
Spring AOP:企业级实战教学
java·后端·spring
lagrahhn1 小时前
IDEA一些提效的方法
java·ide·intellij-idea