为什么要使用 Feign
在使用微服务架构时难免避免各个服务之间的相互调用,各个服务又是以接口的方式暴露,需用Http远程调用,此时就需要用到Feign。
下面简单记录下在敲尚上优选项目时用 Feign 的过程。
怎么使用
假设现在又三个子模块service-activity, service-product, service-client,其中service-product提供接口,service-activity需要调用service-activity中的接口,service-client编写远程调用Feign。
导入依赖
首先需要在service-client模块的pom.xml文件中加入 openfeign 依赖
添加 @EnableDiscoveryClient 注解
在 service-activity, service-product 子模块的启动类上添加 @EnableFeignClients 注解。
定义被调用接口
在 service-product 子模块 ProductInnerController 中定义被调用的方法。
@RestController
@RequestMapping("/api/product")
public class ProductInnerController {
// 根据 skuId 列表得到 sku 信息列表
@PostMapping("inner/findSkuInfoList")
public List<SkuInfo> findSkuInfoList(@RequestBody List<Long> skuIdList){
return skuInfoService.findSkuInfoList(skuIdList);
}
}
定义 FeignClient
在 service-client 中定义相对应方法给 service-activity 调用。
@FeignClient(value = "service-product")
public interface ProductFeignClient {
@PostMapping("/api/product/inner/findSkuInfoList")
// 这里的 url 要和 ProductInnerControler 中的路径相同
List<SkuInfo> findSkuInfoList(@RequestBody List<Long> skuIdList);
}
定义调用接口
在 service-activity 中调用 service-product 中的方法。
@Service
public class ActivityInfoServiceImpl extends ServiceImpl<ActivityInfoMapper, ActivityInfo> implements ActivityInfoService {
@Autowired
private ProductFeignClient productFeignClient;
@Override
public Map<String, Object> findActivityRuleList(Long activityId) {
List<SkuInfo> skuInfoList = productFeignClient.findSkuInfoList(skuIdList);
}
}