一、手写随机负载均衡
1、引入依赖
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
-
- <!--引入nacos discovery-->
- <dependency>
- <groupId>com.alibaba.cloud</groupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
- </dependency>
2、controller定义
- @Resource
- private RestTemplate restTemplate;
-
- @Resource
- private DiscoveryClient discoveryClient;
-
- @RequestMapping("/restLoadbalance")
- public String manualLoadBlance(){
- //1、获取order服务urls
- List<ServiceInstance> instances = this.discoveryClient.getInstances("order");
- List<String> urls = instances.stream().map(instance->instance.getUri().toString()+"/order/query").collect(Collectors.toList());
-
- //2、随机负载请求
- int index = ThreadLocalRandom.current().nextInt(urls.size());
- return this.restTemplate.getForObject(urls.get(index),String.class);
- }
二、LoadBalancer
2.1、API
(1)、引入依赖
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-loadbalancer</artifactId>
- </dependency>
(2)、代码
- //2、loadbalancer api
- @Resource
- private LoadBalancerClient loadBalancerClient;
-
-
- @RequestMapping("/loadbanlancerapi")
- public String loadBanlancerApi(){
- ServiceInstance serviceInstance = this.loadBalancerClient.choose("order");
- return this.restTemplate.getForObject(serviceInstance.getUri().toString()+"/order/query",String.class);
- }
2.2、注解
(1)、引入依赖
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-loadbalancer</artifactId>
- </dependency>
(2)、自定义@LoadBanlancer注解得RestTemplate
- @Bean
- @LoadBalanced // 相当于为restTemplate整合了lb的能力
- public RestTemplate restTemplateLoadBalancer(){
- return new RestTemplate();
- }
(3)、controller代码
- @Resource
- private RestTemplate restTemplateLoadBalancer;
- @RequestMapping("/loadbanlanceraop")
- public String loadBanlancerAop(){
- return this.restTemplateLoadBalancer.getForObject("http://order/order/query",String.class);
- }
三、默认负载算法
默认轮询负载:RoundRobinLoadBalancer
更改默认负载算法:Cloud Native Applications
(1)、自定义负载算法
- public class CustomLoadBalancerConfiguration {
- @Bean
- ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
- LoadBalancerClientFactory loadBalancerClientFactory) {
- String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
- return new RandomLoadBalancer(loadBalancerClientFactory
- .getLazyProvider(name, ServiceInstanceListSupplier.class),
- name);
- }
- }
(2)、启动类增加注解
- @SpringBootApplication
- @LoadBalancerClients(defaultConfiguration = CustomLoadBalancerConfiguration.class)
- public class UserApplicaiton implements ApplicationRunner {
- }
四、源码分析
(1)、RestTemplate流程
(2)、LoadBalancerClient#choose(String serviceId)