Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具。
简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA(高可用)。常用的负载均衡软件 Nginx
重写负载均衡算法看IRule接口
1.导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
2.RestTemplate 使用注解 @LoadBalanced
// @LoadBalanced 让RestTemplate启用客户端负载均衡
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
3,在启动类上添加@EnableEurekaClient
流程:
eureka:
client: #将客户端注册到 eureka 服务列表内
service-url:
defaultZone: http://localhost:7001/eureka/ #这个地址是 7001注册中心在 application.yml 中暴露出来额注册地址
consumer中的defaultZone放在三个7001,,7002,7003的注册中心
privade中的defaultZone也是放在7001,7002,7003的注册中心
feign:使用接口方式调用服务
1.在接口添加@FeignClient
@Component
@FeignClient(value = "MICROSERVICECLOUDPROVIDERDEPTHYSTRIX", fallback = DeptHystrixFallBackService.class)
public interface DeptHystrixService {
@RequestMapping(value = "/dept/hystrix/ok/{id}")
public String deptInfo_Ok(@PathVariable("id") Integer id);
@RequestMapping(value = "/dept/hystrix/timeout/{id}")
public String deptInfo_Timeout(@PathVariable("id") Integer id);
}
2.开启Feign功能
@SpringBootApplication
@EnableFeignClients //开启 OpenFeign 功能
@EnableHystrix //启用 Hystrix
public class MicroServiceCloudConsumerDeptFeignApplication {
public static void main(String[] args) {
SpringApplication.run(MicroServiceCloudConsumerDeptFeignApplication.class, args);
}
}