学习基于记录,而不止于记录。
希望自己能坚持下去~
0.写在前面
最近诸事缠身,博客咕了好久,我有罪。记录一下feign请求遇到的坑吧。
1.开发环境下的feign请求
基本Eureka环境搭建可以参照另一篇博客Eureka整合Seata实现事务控制_2020.05.27,只需要看eureka注册中心搭建即可,至于注册服务的搭建可以参照demo源码的配置,很简单。
启动类
@SpringBootApplication()
@EnableEurekaClient
@EnableFeignClients
public class CustomerprofilesApplication {
...
}
service层
//此处填写的是请求的服务名称,即eureka注册中心的服务名
@FeignClient(value = "platform")
public interface PlatformService {
//此处填写的是请求服务的接口
@RequestMapping("/platform/qxwd/findByWddh")
OperationResponse findByWddh(@RequestParam("wddh")String wddh);
}
被调用的服务controller
@ApiOperation(value = "根据网点代号查询权限网点", notes = "传入网点代号")
@GetMapping("/platform/qxwd/findByWddh")
public OperationResponse findByWddh(@ApiParam(name = "网点代号", required = true)@RequestParam("wddh") String wddh) throws Exception {
QxwdParams1 qxwdParams3 = new QxwdParams1(3, wddh);
return OperationResponse.getInstance(200, OperationResponse.ResponseStatusEnum.NULL, "",
qxwdService.operationWithJSONObjectReturn(qxwdParams3));
}
2.对于https的支持
2.1场景
在把服务部署到服务器时,然后本地运行正常的项目到服务器就掉链子了,feign请求一直显示错误日志exception is feign.RetryableException: Connection refused (Connection refused) executing POST http://....
2.2分析
项目编排方式是k8s+traefik实现部署,请求类型是https,但是feign内部请求却一直是http自然无法正常访问
2.3解决
@FeignClient(value = "platform", url="https://xxx:15000/platform")
public interface PlatformService {
//此处填写的是请求服务的接口
@RequestMapping("/platform/qxwd/findByWddh")
OperationResponse findByWddh(@RequestParam("wddh")String wddh);
}
说白了,在设置访问接口为https请求方式,当然部署生产环境下,肯定不会直接使用显式的的方式,而是采用环境变量注入,比如在我司当前的部署方式下就是k8s的yaml文件中编写:
service层
@FeignClient(value = "wishplatform",url = "${PLATFORM_URL}")
yaml文件
env: # 设置环境变量
- name: PLATFORM_URL
value: "https://xxx:15000/platform"
3.总结
feign请求相比RestTemplate 请求方式,目前使用体验前者明显比后者要好,最主要是代码看着规整入参和返回值明确,消费者和生产者一致;但是后者在实际开发中如果不加以规范和限制团队开发情况下代码可读性极差。另外关于https支持,还得说的一点就是晚上不少都提到了ssl配置之类的,这里我并没有做这些操作,是因为部署架构的原因,这涉及到k8s secret和traefik路由的结合使用,不便详谈。