nacos服务的负载均衡功能演示

服务提供者

第一个服务提供者

@SpringBootApplication
@EnableDiscoveryClient
public class CloudalibabaProviderPayment01Application {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(CloudalibabaProviderPayment01Application.class, args);
    }
    
    @Value("${server.port}")
    private String port; //注入端口,用于辨别是那个provider
    
    
    @RestController
    class EchoController {
    
    
        @RequestMapping(value = "/echo/{string}", method = RequestMethod.GET)
        public String echo(@PathVariable String string) {
    
    
            return "Provider"+port+"收到消息 " + string + "处理完毕!";// 会将端口也输出
        }
    }
}

application.properties文件

server.port=8070
spring.application.name=payment-provider
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

第二个服务提供者

代码一样,修改application.properties中server.port端口为8071用于辨别是哪一个提供者

服务消费者

@SpringBootApplication
@EnableDiscoveryClient
public class CloudalibabaConsumerOrder01Application {
    
    

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

    @Configuration
    public class OrderConfigration {
    
    

        @Bean
        @LoadBalanced  // 注意一定要加上这个
        public RestTemplate restTemplate(){
    
    
            return new RestTemplate();
        }

    }
    
    @RestController
    public class ConsumerController {
    
    

        // 注入上面加入负载均衡的restTemplate类,不使用上面的直接new RestTemplate会报找不到主机错误
        @Autowired
        RestTemplate restTemplate; 
        
        // 获取properties文件中的 http://payment-provider 进行注入
        @Value("${service-url.provider-service}") 
        private String serverURL;

        // 访问该链接,消费者会向提供者发送get请求,让提供者进行处理
        @GetMapping("/consumer/payment/{id}")
        public String paymentInfo(@PathVariable("id") Long id){
    
    
            // 调用服务提供者让其处理
            return restTemplate.getForObject(serverURL+"/echo/"+id,String.class);
        }

    }
}

application.properties

server.port=83
spring.application.name=service-consumer
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
service-url.provider-service=http://payment-provider  # 通过@Value注入,值是上面服务提供者的spring.application.name值

启动服务进行负载均衡测试

将3个服务都启动,信息如下
在这里插入图片描述
在这里插入图片描述
如下通过消费者调用提供者,服务提供者会根据负载均衡进行处理,默认是轮询算法,如果想要使用其它算法例如权重、最快响应时间等算法则需要在@Balance注解上添加即可

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41813208/article/details/108707872