Feign学习笔记

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    (记得搭建一个包含相关组件的项目进行实验).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值