Spring Cloud Ribbon基于Netflix Ribbon实现,属于客户端(服务消费者)的负载均衡。client从服务注册中心Eureka获取到服务列表,然后通过轮询的方式从获取到的服务中选取一个发出请求。
Spring Cloud Ribbon使用很简单,最常用的使用方法如下:
@LoadBalanced @Bean public RestTemplate restTemplate(){ return new RestTemplate(); }在RestTemplate上加上注解@LoadBalanced即可开启负载均衡,这样使用RestTemplate调用服务时会轮询服务来达到负载均衡的目的。
测试:
1.建立注册Eureka注册中心
server: port: 11500 spring: application: name: eurka-server #eureka注册中心配置 eureka: instance: hostname: localhost client: registerWithEureka: false fetchRegistry: false serviceUrl: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/2.建一个服务提供者service-user
server: port: 0 spring: application: name: service-user eureka: client: serviceUrl: defaultZone: http://localhost:11500/eureka/ #指定不同的实例名称,加一个随机数来区分(非端口号) instance: instance-id: ${spring.application.name}-${random.int[100,999]}暴露对外调用接口(Controller):
@RequestMapping("/test") public Object test(){ return "SERVICE-ID: "+serviceInstance.getServiceId()+" , PORT: "+serviceInstance.getPort(); }以service-id+port的形式返回以区别不同实例
注意这里的server.port,采用随机端口的形式来启动多个实例。
随机端口有两种写法:
一种是用Spring提供的${random.int[num1,num2]}来指定范围内的端口;
另一种是直接用0,将会分配一个未被使用的随机端口。
使用第一种会造成实例端口与注册中心注册的端口不一致,因为实例启动时时,从配置文件获取了一次随机端口,而注册到配置中心时,又从配置文件获取了一次随机端口,前后两次获取到的随机值不同,导致无吴无法调用。
因此使用第二种方式,但是需要指定不同的实例名称,不然依旧是同一个实例。
3.新建一个服务消费者client-web
server: port: 11503 spring: application: name: client-web eureka: client: serviceUrl: defaultZone: http://localhost:11500/eureka/暴露对外访问接口(Controller):
private final RestTemplate restTemplate; @Autowired public TestController(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @RequestMapping("test") public String test(){ String res = restTemplate.getForObject("http://service-user/test",String.class); return res; }先启动注册中心,在启动其他两个。
可以看到两个service-user实例已经注册到了注册中心。
然后访问http://localhost:11503两次,得到的返回结果如下:
//第一次 SERVICE-ID: service-user , PORT: 59430 //第二次 SERVICE-ID: service-user , PORT: 59420说明请求已被分发到两个实例上,实现了负载均衡。