Feign是一种声明式调用组件, 在用微服务架构的时候,项目中会用restTemplate模板来转发请求到相应的实例当中(@LoadBalanced 负载均衡回忆一下),然後用模板的话会有一堆冗余代码(参数拼接啊, 类的构造、格式设置等等很繁琐, 繁琐就容易出错).
// 以下是restTemplate模板代码
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<Object> entity = new HttpEntity<>(param, headers);
ResponseEntity<BaseResult> response = restTemplate.postForEntity(addTask, entity, BaseResult.class, user.getUserId(), user.isAdmin(), user.getUsername(), user.getOrgId(), user.getOrgName());
return response.getBody();
如果用Feign来标注一下相应的服务,我们就可以完成这个冗余代码的封装了.
@FeignClient(name = "${xxxxxxxx}", configuration = FeignConfig.class)
public interface xxxxFeignService {
@RequestMapping(value = "/xxxxxx/jobGet", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
BaseResult<String> jobGet(@RequestBody XXX xxx) throws ApiException;
@RequestMapping(value = "/xxxxxxxxx/JobNew", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
BaseResult<String> JobNew(@RequestBody String XXXX) throws ApiException;
@RequestMapping(value = "/XXXXXX/JobCancel", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
BaseResult<Object> JobCancel(@RequestBody XXXX xxx) throws ApiException;
}
name = 服务的ip地址, 然后我们就可以很方便的去申请调用相关的服务实例了(直接xxxService.jobGet这样), Spring Cloud Feign 具备可插拔的注解支持,在启动类中新增@EnableFeignClients注解开启Spring Cloud Feign的支持功能,Feign还能很轻松的实现降级代码, 通过接口的实现类来覆盖该方法即可
@FeignClient("http://notification-service")
public interface NotificationResource {
@RequestMapping(value = "/notifications", method = GET)
List<Notification> findAll();
}
public class NotificationResourceImpl implements NotificationResource {
@Override
public List<Notification> findAll() {
return new ArrayList<>();
}
}
Feign、Hystrix、Ribbon的关系:https://www.jianshu.com/p/51c5e28c9574 (记得搭建一个包含相关组件的项目进行实验).