1,Ribbon(瑞本)负载均衡调用
是什么
spring cloud ribbon 是一套客户端的负载均衡工具
主要用来:客户端的软件负载均衡算法和服务的调用
做什么
负载均衡+RestTemplate调用
LB负载均衡:将用户请求平摊到多个服务器上,从而达到系统的HA(高可用)
ribbon是本地负载均衡:在调用微服务接口时,会在注册中心中获取注册信息服务列表之后缓存到jvm本地,从而在本地实现rpc的远程调用;
nginx是服务器负载均衡:客户端所用请求交给nginx,然后由nginx实现转发请求.即负载均衡是由服务端实现的。
ribbon目前也进入了维护模式
2,Ribbon的使用
pom
下面这个依赖自带了 Ribbon的依赖。所以有这个注解就不需要引入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
如果没有引入上面的注解,就需要特德引入ribbon的注解
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
3,resttemplate的使用
getForObject的方法/getForEntity的方法
@RestController
@Slf4j
public class OrderController {
public static final String url = "http://CLOUD-PAYMENT-SERVICE";
@Resource
private RestTemplate restTemplate;
@GetMapping("/consumer/payment/getForEntity/{id}")
public CommonResult<Payment> getForEntitt(@PathVariable("id")Long id){
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(url + "/getPaymentById/" + id, CommonResult.class);
if (entity.getStatusCode().is2xxSuccessful()){
return entity.getBody();
}else {
return new CommonResult<>(444,"操作失败");
}
}
}
postForObject/PostEntity
GET请求方法
POST请求方法
4,Ribbon的核心组件是IRule(爱瑞了)
IRule:根据特定算法从服务器列表中选取一个要访问的服务;
如何替换算法,把轮询改为随机
官网明确警告:这个自定义配置类不能放在@componentScan所扫描的当前包以及子包下。否则我们的自定义配置类会被所有的Ribbon客户端所共享,达不到特殊化制定的目的。
在springcloud中,@componentScan的注解是在启动类注解@SpringBootApplication之下;
要创建配置类的包:
新建规格类
@Configuration
public class MySelfRule {
@Bean
public IRule myRule() {
// 定义为随机
return new RoundRobinRule();
}
}
在主启动类添加@RibbonClient
@SpringBootApplication
@EnableEurekaClient
//CLOUD-PAYMENT-SERVICE是服务注册中心的服务名
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
public class OraderMain80 {
public static void main(String[] args) {
SpringApplication.run(OraderMain80.class,args);
}
}
启动测试验证