Demonstration of load balancing function of nacos service

service providers

第一个服务提供者

@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.propertiesfile

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

第二个服务提供者

The code is the same, modify the server.port port in application.properties to 8071 to identify which provider

Service consumer

@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值

Start the service for load balancing test

Start all three services. The information is as
Insert picture description here
Insert picture description here
follows. The provider is called by the consumer. The service provider will process according to the load balance. The default is the polling algorithm. If you want to use other algorithms such as weights, fastest response time, etc., you need Just add it to the @Balance annotation

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41813208/article/details/108707872