SpringCloud OpenFeign模板化远程通信
有头发的程序猿! 人气:01. 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") Map<String, Object> getTime(@RequestBody Map<String, Object> params); }
客户端代码
@Resource UserService userService; @GetMapping("/test") public String test() throws Exception { log.info("openFeign -- start"); Map<String, Object> time = userService.getTime(resMap); log.info("openFeign -- {}", time); return template + ":" + time; }
1.4.服务端暴露接口
@PostMapping("/postTime") public Map<String, Object> getTime(@RequestBody Map<String, 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}
加载全部内容