Ribbon笔记
ribbon的作用
ribbon一个客户端负载均衡工具,为分布式应用提供负载均衡(LoadBalanced)和服用调用功能(一般来说,服务调用通过OpenFeign或其他微服务远程调用组件实现),ribbon通过一些负载均衡算法将对微服务的请求进行分配,保证各个实例承担的请求负载相对平衡,达到均衡负载的作用。
ribbon用法
1.导入依赖
新的eureka依赖中已经整合了ribbon相关依赖,所以如果在pom文件中已经导入了以下依赖,就不用在另外导ribbon依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2.配置ribbon
如果都使用默认配置的话,可以不对ribbon进行任何配置
3.消费服务
引入了ribbon后,就可以通过负载均衡的模式去访问其他微服务了
3.1 通过RestTemplate访问其他服务
首先通过springboot的@SpringBootConfiguration注解和@Bean注解,向容器中注入一个RestTemplate对象,并且需要在注入对象的方法上标注@LoadBalanced注解,这样后续通过该RestTemplate访问其他微服务的时候,就会进行负载均衡,代码如下:
package com.yichengbo.config;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootConfiguration
public class ApplicationConfiguration {
@Bean
@LoadBalanced // 负载均衡注解
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
然后使用RestTemplate接口提供的API调用其他微服务,调服务HELLO-SERVICE的代码如下:
package com.yichengbo.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ConsumerRest {
@Autowired
private RestTemplate restTemplate;
// hello-service已经注册到了eureka上,所以可以通过服务名调
private static final String HELLO_SERVICE_URL = "http://HELLO-SERVICE/hello";
// private static final String HELLO_SERVICE_URL = "http://localhost:8001/hello";
@GetMapping("/consume-hello")
public String consumeHelloService(){
return restTemplate.getForEntity(HELLO_SERVICE_URL,String.class).getBody();
}
}
HELLO-SERVICE服务的/hello能打印出当前所访问的微服务的server.port(代码如下),启动两个HELLO-SERVICE实例(端口分别为8001和8002),多次调消费者的/consume-hello接口,会交替打印"Hello from port 8001"、“Hello from port 8002”。
package com.yichengbo.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloRest {
@Autowired
private Environment environment;
@GetMapping("/hello")
public String hello(){
String port = environment.getProperty("local.server.port");
return "Hello from port " + port;
}
}