基于SpringCloud的OpenFeign模板化远程通信如何实现
1. openFeign实现
基于spring-boot-starter-parent 2.6.8,spring-cloud-dependencies 2021.0.3
,一个order服务一个user服务
1.1 pom依赖
!--nacos服务注册与发现--> dependency> groupId> com.alibaba.cloud/groupId> artifactId> spring-cloud-starter-alibaba-nacos-discovery/artifactId> version> 2021.0.1.0/version> /dependency> !--远程服务调用--> dependency> groupId> org.springframework.cloud/groupId> artifactId> spring-cloud-loadbalancer/artifactId> /dependency> !--服务调用feign--> dependency> groupId> org.springframework.cloud/groupId> artifactId> spring-cloud-starter-openfeign/artifactId> /dependency>
1.2 yaml配置
order调用端,配置的超时设置注释掉了只为记录
spring:
application:
name: orderservice
cloud:
#找对应网段的网卡 不配置内部服务就走外网
inetutils:
preferred-networks: 192.168.0
nacos:
discovery:
server-addr: 192.168.0.221:8848
#feign:
# client:
# config:
# #default设置的是全局超时时间,对所有的openFeign接口服务都生效 默认60s超时
# default:
# connectTimeout: 5000
# readTimeout: 5000
# #为某个服务设置超时时间 优先于全局
# userservice:
# connectTimeout: 5000
# readTimeout: 5000
user服务仅需要注册
spring:
application:
name: userservice
cloud:
#找对应网段的网卡 不配置内部服务就走外网
inetutils:
preferred-networks: 192.168.0
nacos:
discovery:
server-addr: 192.168.0.221:8848
远程调用依赖于注册中心,这里用的是nacos,其他的eureka也可以的
1.3 客户端调用代码
- 启动类上添加
@EnableFeignClients
注解 - api接口,可以单独放在api包
@FeignClient(value = "userservice") //没有注册中心的服务调用使用 testFeign/随便写 //@FeignClient(value = "testFeign",url = "http://192.168.0.199:7540") public interface UserService { //默认是@RequestBody注解参数 //如果使用其他注解一定要带上value 否者会报错 RequestParam.value() was empty on parameter 1 @GetMapping("/getTime/{ uuid} ") String getTime(@PathVariable("uuid") String uuid, @RequestParam("name") String name); @PostMapping("/postTime") MapString, Object> getTime(@RequestBody MapString, Object> params); }
客户端代码
@Resource UserService userService; @GetMapping("/test") public String test() throws Exception { log.info("openFeign -- start"); MapString, Object> time = userService.getTime(resMap); log.info("openFeign -- { } ", time); return template + ":" + time; }
1.4.服务端暴露接口
@PostMapping("/postTime") public MapString, Object> getTime(@RequestBody MapString, Object> params) { params.put("time", new Date().getTime()); return params; }
1.5.测试日志
c.e.order.controller.OrderController : openFeign -- start
c.e.order.controller.OrderController : openFeign -- {
aaaa=bbbb, time=1657187048104}
感谢各位的阅读,以上就是“基于SpringCloud的OpenFeign模板化远程通信如何实现”的内容了,通过以上内容的阐述,相信大家对基于SpringCloud的OpenFeign模板化远程通信如何实现已经有了进一步的了解,如果想要了解更多相关的内容,欢迎关注网络,网络将为大家推送更多相关知识点的文章。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 基于SpringCloud的OpenFeign模板化远程通信如何实现
本文地址: https://pptw.com/jishu/652427.html