系列八、Spring Cloud LoadBalancer

一、Spring Cloud LoadBalancer

1.1、概述

        上一篇文章介绍了Ribbon的基本知识和使用方法,我们知道Ribbon当前已处于维护模式,不再提供新功能。基于此,Spring官方发布了一套未来替代Ribbon的解决方案,即:

Spring Cloud LoadBalancer。说明:2.2.6.RELEASE版本仅仅支持轮询算法,其他暂不支持!Spring Cloud LoadBalancer只是一种未来的替代方案,现在主流还是使用ribbon

1.2、官网

https://docs.spring.io/spring-cloud-commons/reference/spring-cloud-commons/loadbalancer.html

1.3、实战

1.3.1、项目概览

系列八、Spring Cloud LoadBalancer_第1张图片

1.3.2、pom



	
	
		org.springframework.cloud
		spring-cloud-starter-loadbalancer
	

	
	
		org.springframework.boot
		spring-boot-starter-web
	

	
	
		com.alibaba.cloud
		spring-cloud-starter-alibaba-nacos-discovery
		
			
				org.springframework.cloud
				spring-cloud-starter-netflix-ribbon
			
		
	

1.3.3、yml 

server:
  port: 8001

spring:
  application:
    name: order-service-loadbalancer-nacos
  cloud:
    nacos:
      server-addr:  xxx
      discovery:
        username: nacos
        password: nacos
    loadbalancer:
      ribbon:
        enabled: false

 1.3.4、MySpringConfig

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2024/1/2 8:37
 * @Description:
 */
@Configuration
public class MySpringConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        RestTemplate restTemplate = builder.build();
        return restTemplate;
    }

}

1.3.5、OrderLoadBalancerController

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2024/1/2 8:21
 * @Description:
 */
@Slf4j
@RequestMapping("/order")
@RestController
public class OrderLoadBalancerController {

    @Resource
    private RestTemplate restTemplate;

    // public static final String INVOKE_URL = "http://localhost:8002/stock/reduceStock";
    public static final String INVOKE_URL = "http://stock-service-nacos/stock/reduceStock";

    @GetMapping("/placingOrder")
    public String placingOrder() {
        log.info("下单成功!");
        String result = restTemplate.getForObject(INVOKE_URL, String.class);
        log.info("result:{}", result);
        return "下单成功********O(∩_∩)O";
    }

}

1.3.6、主启动

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2024/1/3 9:38
 * @Description:
 */
@SpringBootApplication
public class OrderServiceLoadBalancer8001MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderServiceLoadBalancer8001MainApplication.class, args);
    }


}

你可能感兴趣的:(Spring,Cloud,Alibaba系列,LoadBalancer,cloud,alibaba)