SpringCloud整合Open-Feign负载均衡
一、前言
提示:本文讲到的代码部分来自上文 上文链接地址
二、服务调用
1、添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2、配置启动类注解
启动类增加@EnableFeignClients
3、新建接口用于调用服务
@FeignClient(value = "spring-other1")
public interface OtherService2 {
@RequestMapping("/other1/getusername2")
String getOther1UserName2(@RequestParam("name") String userName);
}
4、调用方法
@RestController
@RequestMapping("other2")
public class OtherController2 {
@Autowired
private OtherService2 otherService2;
@RequestMapping("getusername4")
String getUserName4(@RequestParam("name") String userName) {
String other1UserName2 = otherService2.getOther1UserName2(userName);
return other1UserName2 + "-该字段为other2的getUserName反回的数据";
}
}
效果图
5、post方式(同理)
1、被调用方Controller
@RestController
@RequestMapping("other1")
public class OtherController1 {
@RequestMapping("getusername3")
String postOther1UserName2(@RequestBody User user){
return user.getName()+"-该字段为other1的getUserName3反回的数据";
}
}
2、调用方Service
@FeignClient(value = "spring-other1")
public interface OtherService2 {
@RequestMapping("/other1/getusername3")
String postOther1UserName2(@RequestBody User user);
}
3、调用方Controller
@RestController
@RequestMapping("other2")
public class OtherController2 {
@Autowired
private OtherService2 otherService2;
@RequestMapping("getusername5")
String getusername5(@RequestBody User user) {
String other1UserName2 = otherService2.postOther1UserName2(user);
return other1UserName2 + "-该字段为other2的getUserName反回的数据";
}
}
效果图
6、总结
Ribbon和feign两个的区别和选择
选择feign
默认集成了ribbon
写起来更加思路清晰和方便
采用注解方式进行配置,配置熔断等方式方便
|