Ribbon 是干什么的,做负载均衡的。
有很多个providers,consumer调用哪个provider?根据特点算法从服务列表中选取一个要访问的服务。
consumer端的实现 consumer : 需要支持可设定算法的负载均衡功能 要改3个地方。
下面以order80为例
1.添加依赖:
2.controller +-RestTemplate
3.负载均衡策略的设定
1.添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2.controller +-RestTemplate
2.1 RestTemplate 的使用不是直接Importclass 是需要写config配置类的
@Configuration
public class ApplicationContextConfig
{
@Bean
@LoadBalanced
public RestTemplate getRestTemplate()
{
return new RestTemplate();
}
}
2.2 RestTemplate在Controller里被调用
@Resource
private RestTemplate restTemplate;
//post
@GetMapping("/consumer/payment/create")
public CommonResult<Payment> create(Payment payment) {
return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
}
//getObject 返回的是 响应体
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
}
//getEntity 返回的是 响应头、状态码、响应体
@GetMapping("/consumer/payment/getForEntity/{id}")
public CommonResult<Payment> getPayment2(@PathVariable("id") Long id)
{
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
if(entity.getStatusCode().is2xxSuccessful()){
return entity.getBody();
}else{
return new CommonResult<>(444,"操作失败");
}
}
3.负载均衡策略的设定
实现步骤:
3.1分包建类 @configuration @Bean
Rebbion的包不能放在@ComponentScan下
@Configuration
public class MySelfRule {
@Bean
public IRule myRule()
{
return new RandomRule();//定义为随机
}
}
3.2 主类添加@RibbonClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration= MySelfRule.class)
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration= MySelfRule.class)
public class OrderMain80
{
public static void main(String[] args) {
SpringApplication.run(OrderMain80.class, args);
}
}
3.3 测试
http://localhost/consumer/payment/get/1
8001 8002 端口将随机出现,以前是顺序出现。