Ribbon
Ribbon可以在通过客户端中配置的ribbonServerList服务端列表去轮询访问以达到均衡负载的作用。
当Ribbon与Eureka联合使用时,ribbonServerList会被DiscoveryEnabledNIWSServerList重写,扩展成从Eureka注册中心中获取服务端列表。
同时它也会用NIWSDiscoveryPing来取代IPing,它将职责委托给Eureka来确定服务端是否已经启动。
操作:
再起一台服务,修改端口
此时在看注册中心
使用Ribbon实现客户端负载均衡的消费者
构建一个基本Spring Boot项目,并在pom.xml中加入如下内容:
4.0.0 com.clc clc-client 0.0.1-SNAPSHOT jar registry Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 1.3.5.RELEASE org.springframework.cloud spring-cloud-starter-ribbon org.springframework.cloud spring-cloud-starter-eureka org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-dependencies Brixton.RELEASE pom import
在应用主类中,通过@EnableDiscoveryClient
注解来添加发现服务能力。创建RestTemplate实例,并通过@LoadBalanced
注解开启均衡负载能力。
@EnableDiscoveryClient@SpringBootApplicationpublic class ClientApplication { @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(ClientApplication.class, args); }}
创建ConsumerController
来消费COMPUTE-SERVICE
的add服务。通过直接RestTemplate来调用服务,计算10 + 20的值。
package com.clc.client.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.client.RestTemplate;@RestControllerpublic class ConsumerController { @Autowired RestTemplate restTemplate; @RequestMapping(value = "/add", method = RequestMethod.GET) public String add() { return restTemplate.getForEntity("http://clc-service/add?a=10&b=20", String.class).getBody(); }}
application.properties
中配置eureka服务注册中心
#服务名spring.application.name=clc-clientserver.port=9004#注册中心地址eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/
启动该应用,并访问两次:
然后,打开clc-service的两个服务提供方,分别输出了类似下面的日志内容:
- 端口为9002服务提供端的日志:
2018-08-31 15:40:39.766 INFO 4758 --- [io-9002-exec-10] c.c.s.c.ComputeController@7c1c5936 : /add, host:192.168.43.85, service_id:clc-service结果:2
- 端口为9003服务提供端的日志:
2018-08-31 15:40:45.278 INFO 4802 --- [nio-9003-exec-3] c.c.s.c.ComputeController@47289387 : /add, host:192.168.43.85, service_id:clc-service结果:2
posted @ 2018-08-31 15:42 阅读( ...) 评论( ...)