SpringCloud从入门到住院(二):feign实现比ribbon更加简单的负载均衡
转载请注明来源
https://blog.****.net/SingingFisher/article/details/88694562
1、前言
大家好,我是脚气哥!作为一个只会ctrl c、crl v的菜逼,我将带领众多菜逼一起学习SpringCloud!
项目地址:https://gitee.com/SiningFish/zed ,大家可以前往查看。如果觉得讲的知识有帮助,希望可以给我点个star哦。
推荐图书
- 《Spring Cloud微服务架构开发实战》
- 《Spring Cloud与Docker微服务架构实战》
2、简介
在上一篇中我们介绍了SpringCloud服务注册发现与通过ribbon进行负载均衡,爽是很爽,不过,在服务消费者的controller中通过如下方式访问,好像有点过于酸爽了:
@GetMapping("/user/{id}")
public Result queryById(@PathVariable("id") Long id){
return restTemplate.getForEntity("http://ZED-SERVICE-USER/user/{id}", Result.class, id).getBody();
}
一个controller我要写这么一个,十个就要写十个?还需要考虑多个参数怎么搞,好像有点烦了。
幸好,有一个叫feign的东西,可以解决这个问题。
3、项目讲解
你可以直接把我的gitee上代码clone下来,也可以自己创建。本文档对应a2分支,下载直接用https://gitee.com/SiningFish/zed/tree/a2/
,然后用IDEA打开就可以了。
3.1 代码
代码在上一篇的示例代码上进行修改,上一篇代码地址https://gitee.com/SiningFish/zed/tree/a1/
,直接git克隆下来就OK了。
3.2 修改内容
3.2.1 父模块的pom.xml
文件
properties
中添加feign版本
<spring-cloud-feign.version>1.4.2.RELEASE</spring-cloud-feign.version>
3.2.2 consumer模块
-
pom.xml
文件
删除ribbon依赖,添加feign依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>${spring-cloud-feign.version}</version>
</dependency>
- 删除配置了RestTemplate的配置文件
- 添加
UserService
@FeignClient("ZED-SERVICE-USER")
public interface UserService {
@GetMapping("/user/{id}")
public Result getById(@PathVariable("id") Long id);
}
对应了User模块的controller,url、参数、返回值啥的都一样。
4. 修改controller
@RestController
@RequestMapping("/consumer")
@AllArgsConstructor
public class ConsumerController {
private UserService userService;
@GetMapping("/user/{id}")
public Result getById(@PathVariable("id") Long id){
return userService.getById(id);
}
}
直接通过UserService调用。
4、测试
依次运行eureka服务器、两个user服务、consumer服务之后,进行测试
4.1 直接访问ZED-SERVICE-USER
7.2 通过ZED-SERVICE-CONSUMER多次访问
- 第一次
- 第二次
7.3 结论
feign可以和ribbon一样做到负载均衡,且更加方便快捷。
8、欢迎提问
转载请注明来源
https://blog.****.net/SingingFisher/article/details/88694562