SpringCloud(六):Ribbon示例

来源:互联网 发布:闪电站小猪知乎 编辑:程序博客网 时间:2024/05/17 07:29

基于博客已有的项目所做更改。

链接:http://pan.baidu.com/s/1bpnNvRL 密码:ffnl

一、建立ribbon的项目

将microservice-consumer-movie复制粘贴一下,重新命名为:microservice-consumer-movie-ribbon

二、修改命名

1、更改pom文件

<artifactId>microservice-consumer-movie-ribbon</artifactId>
2、更改appplication.yml

spring:  application:    name: microservice-consumer-movie-ribbon

三、在microservice-spring-cloud的pom文件中添加模块

<module>microservice-consumer-movie-ribbon</module>

四、添加Ribbon的jar包

官网:

How to Include Ribbon

To include Ribbon in your project use the starter with group org.springframework.cloud and artifact id spring-cloud-starter-ribbon.

因为eureka的jar包中已经包含了ribbon的jar包,所以不必再添加。

五、加负载均衡的注解@LoadBalanced

在 ConsumerMovieRibbonApplication.java的restTemplate()方法上添加

@LoadBalancedpublic RestTemplate restTemplate(){return new RestTemplate();}

六、去掉硬编码

将url地址替换为注册到eureka中的微服务名称。

修改MovieController.java,去掉url配置,url换成微服务名称

//@Value("${user.userServicePath}")//private String userServicePath;@GetMapping("/movie/{id}")private User findById(@PathVariable Long id) {return this.restTemplate.getForObject(this.userServicePath+id, User.class);}

修改application.yml,去掉如下url配置

user:  userServicePath: http://localhost:7900/simple/

七、修改端口

在application.yml中

server:  port: 8010

八、启动

先启动eureka,然后再启动用户微服务,启动两个端口7900和7901,修改application.yml便可以。最后启动ribbon。

九、启动成功后,访问页面,输入url地址:http://localhost:8761/


由上图可知,eureka中注册了两个提供者实例和一个消费者实例。

十、输入url地址:localhost:8010/movie/1,刷新四次

可以看到启动的两个提供者的控制台各输出两次查询日志。这是负载均衡轮询的一种体现。


小结

到这里,ribbon的示例就结束了。这里Ribbon的使用完美地解决了之前遗留的硬编码问题和负载问题。负载均衡的关键是加的@LoadBalance注解。完整的项目源码地址将在ribbon讲解结束的博客中分享。尽情期待。。。

原创粉丝点击