spring cloud alibaba nacos 负载均衡

nacos天生就支持负载均衡,为什么呢,我们看看下图就知道了,nacos已经集成了ribbon,所以当同一个服务出现了多个实例之后会默认使用轮训机制进行负载均衡

spring cloud alibaba nacos 负载均衡_第1张图片

 

步骤一:

上篇我们创建了nacos的提供者微服务,参考https://blog.csdn.net/weixin_42214548/article/details/107280560

所以我们创建一个消费者微服务spring-cloud-consumer-nacos,并添加依赖

 
        
            com.alibaba.cloud
            spring-cloud-starter-alibaba-nacos-discovery
        
        
            com.alibaba.cloud
            spring-cloud-starter-alibaba-nacos-config
        
        
            org.springframework.boot
            spring-boot-starter-web
        
    

 

步骤二:

创建启动类,并且RestTemplate设置为负载

@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

 

步骤三:

创建controller请求

@RestController
public class TestController {
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/echo", method = RequestMethod.GET)
    public String echo() {
        return restTemplate.getForObject("http://nacos-provider/provider/test", String.class);
    }
}

 

步骤四:

消费者服务以及就绪,现在我们准备了两个提供者,端口分别为: 9002 , 9003

spring cloud alibaba nacos 负载均衡_第2张图片

 

我们通过调用http://localhost:9001/echo 消费者服务的请求,来验证下是否能够实现负载均衡

 

第一次请求:

spring cloud alibaba nacos 负载均衡_第3张图片

 

第二次请求:

spring cloud alibaba nacos 负载均衡_第4张图片

 

第三次请求:

spring cloud alibaba nacos 负载均衡_第5张图片

 

通过测试我们发现了,服务都完美实现了负载均衡

你可能感兴趣的:(springcloud)