feign
大约 1 分钟languagejava
概述
微服务架构中通过 feign 通信,请求其他微服务调用其他微服务的 API
特性
制作一个 feign 客户端的注意点
- 使用接口
interface定义一个客户端,并使用注解@FeignClient,注意填写该注解的三个属性contextId,value,fallbackFactory。第三个属性是熔断降级时用到的类 - 调用方法的函数签名可以直接拷贝目标微服务
controller中的方法,注意返回结果要使用统一返回对象包裹CommonResponse - 一般在模块下创建目录
feign作为客户端接口路径,创建feign/hystrix作为熔断降级策略的实现类的目录。例如有接口feign/SureGoodsClient.java,同时制作类feign/hystrix/GoodsClientHystrix.java实现前面的接口 - 一般都要使用
fallbackFactory制作抛出异常的功能,不使用fallback,因为后者无法抛出异常,无法得知系统出现的问题
package com.xdf.ecommerce.feign;
import com.xdf.ecommerce.goods.GoodsInfo;
import com.xdf.ecommerce.vo.CommonResponse;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.time.LocalDateTime;
import java.util.List;
/**
* 在 e-commerce-mvc-config 中制作了使用统一响应对象
* 通过 feign 接受到的响应结果都是通过 CommonResponse 包装之后的
* 除非使用了注解 IgnoreResponseAdvice 忽略返回结果时包装
*
* 属性 contextId = beanId
* 属性 value = 本接口调用的微服务模块的名称 = 微服务配置文件bootstrap.yml # spring.application.name
* @author chanchaw
* @create 2025-11-11 22:11
*/
@FeignClient(contextId = "NotSecuredGoodsClient", value = "e-commerce-goods-service")
public interface NotSecuredGoodsClient {
@PostMapping("/ecommerce-goods-service/asyncGoods/test")
CommonResponse<LocalDateTime> test();
@PostMapping("/ecommerce-goods-service/goods/getGoodsInfo8Id")
CommonResponse<List<GoodsInfo>> getGoodsInfo8Id(@RequestBody List<Long> ids);
}
