什么是负载均衡?
负载均衡就是将负担(工作任务,访问请求)进行分摊到多个操作单元(服务器,组件)上进行执行。
什么是Ribbon?
ribbon是基于netfilx ribbon实现的一个工作在consumer端的负载均衡工具,提供了很多负载均衡策略:轮询策略、随机策略
我们不需要去引入ribbon的依赖,因为在nacos里面已经集成了ribbon的依赖
基于ribbon实现负载均衡
1.修改ribbon_consumer
1.1.ConfigBean
负载均衡接口:com.netflix.loadbalancer.IRule
如果要使用随机策略,在配置文件中添加
@Bean
public IRule iRule(){
return new RandomRule();
}
package com.bjpowernode.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ConfigBean {
@Bean
/**
* 添加了@LoadBalanced注解之后,Ribbon会给restTemplate请求添加一个拦截器,在拦截器中获取
* 注册中心的所有可用服务,通过获取到的服务信息(ip,port)替换 serviceId 实现负载请求。
*/
//@LoadBalanced //开启负载均衡
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
//随机策略
@Bean
public IRule iRule() {
return new RandomRule();
}
}
1.2 controller
package com.bjpowernode.controller;
import com.bjpowernode.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.Random;
@RestController
@RequestMapping(value = "/consumer")
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@RequestMapping(value = "/getUserById/{id}")
public User getUserById(@PathVariable Integer id) {
//不使用ribbon:ip:port
//String serviceUrl = "127.0.0.1:9090";
//使用ribbon:不再使用ip:port的方式,而是改成了serviceId(即Nacos中注册的服务名称)
return restTemplate.getForObject("http://"ribbon-provider
"/provider/getUserById/" + id, User.class);
}
}