这篇文章主要介绍了SpringCloud中@FeignClient()注解的使用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教。
文章目录
1、@FeignClient()注解的使用
2、@FeignClient标签的常用属性
SpringCloud搭建各种微服务之后,服务间通常存在相互调用的需求,SpringCloud提供了@FeignClient 注解非常优雅的解决了这个问题
3、@FeignClient()简单样例
首先,保证所需要服务都注册成功
我一共有三个服务注册成功。分别为:服务A、服务B、服务C
如下:
给它们的角色
服务A:接口提供方
服务B:接口使用方
服务C:编写远程调用Feign
3.1、调用Get请求带参接口
服务B调用服务A中的getTest-a,有参数a和b
服务A的controller层
@GetMapping("getTest-a")
public R<?> getTest(String a, Integer b){
String data = "服务A返回信息===a:" + a + "===b:" + b;
return R.ok(data);
}
服务C中创建TestClient,用于给服务B调用
注意:
Feign 调用接口参数问题;多个值传递用:@RequestParam(“xxx”)
单个值传递:@RequestBody
@FeignClient(contextId = "testClient", value = "服务A")
public interface TestClient {
@GetMapping("getTest-a")
R<?> getTest(@RequestParam("a") String a, @RequestParam("b") Integer b);
}
服务B调用
// 注入服务C的TestClient
@Autowired
private TestClient testClient;
@GetMapping("getTest-b")
public R<?> getTest(){
return testClient.getTest("服务B成功调用", 666);
}
测试
3.2、调用Post请求不带参接口
服务B调用服务A中的postTest-a,无参数
服务A的controller层
@GetMapping("getTest-a")
public R<?> getTest(String a, Integer b){
String data = "服务A返回信息===a:" + a + "===b:" + b;
return R.ok(data);
}
@PostMapping("postTest-a")
public R<?> postTest(){
String data = "服务A返回信息";
return R.ok(data);
}
服务C的TestClient添加接口
@FeignClient(contextId = "testClient", value = "服务A")
public interface TestClient {
@GetMapping("getTest-a")
R<?> getTest(@RequestParam("a") String a, @RequestParam("b") Integer b);
@PostMapping("postTest-a")
R<?> postTest();
}
服务B调用
@GetMapping("getTest-b")
public R<?> getTest(){
return testClient.getTest("服务B成功调用", 666);
}
@PostMapping("postTest-b")
public R<?> postTest(){
return testClient.postTest();
}
测试
如果觉得不错,可以点赞+收藏或者关注下博主。感谢阅读! |