@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;
    }
}
相关推荐
tokepson4 分钟前
Mysql下载部署方法备份(Windows/Linux)
linux·服务器·windows·mysql
韩师学子--小倪1 小时前
fastjson与gson的toString差异
java·json
Drawing stars1 小时前
JAVA后端 前端 大模型应用 学习路线
java·前端·学习
nbsaas-boot1 小时前
SQL Server 存储过程开发规范(公司内部模板)
java·服务器·数据库
行百里er2 小时前
用 ThreadLocal + Deque 打造一个“线程专属的调用栈” —— Spring Insight 的上下文管理术
java·后端·架构
玄〤2 小时前
黑马点评中 VoucherOrderServiceImpl 实现类中的一人一单实现解析(单机部署)
java·数据库·redis·笔记·后端·mybatis·springboot
zz_nj2 小时前
工作的环境
linux·运维·服务器
J_liaty2 小时前
Spring Boot拦截器与过滤器深度解析
java·spring boot·后端·interceptor·filter
亲爱的非洲野猪3 小时前
Java锁机制八股文
java·开发语言
rgeshfgreh3 小时前
C++字符串处理:STL string终极指南
java·jvm·算法