④. 基于Nacos的服务消费者
为什么nacos支持负载均衡?
- ①. 新建Module:cloudalibaba-consumer-nacos-order83
- ②.POM
<dependencies> <!--SpringCloud ailibaba nacos --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>com.atguigu.springcloud</groupId> <artifactId>cloud-api-commons</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
③. YML
server: port: 83 spring: application: name: nacos-order-consumer cloud: nacos: discovery: server-addr: localhost:8848 service-url: nacos-user-service: http://nacos-payment-provider
④. 主启动
@EnableDiscoveryClient @SpringBootApplication public class OrderNacosMain83{ public static void main(String[] args){ SpringApplication.run(OrderNacosMain83.class,args); } }
⑤. 业务类
- ApplicationContextBean:配置负载均衡
- OrderNacosController:获取到nacos中配置的文件信息
@Configuration public class ApplicationContextBean { @Bean @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); } }
@SuppressWarnings("all") @RestController @Slf4j public class OrderNacosController { @Resource private RestTemplate restTemplate; @Value("${service-url.nacos-user-service}") private String serverURL; @GetMapping(value = "/consumer/payment/nacos/{id}") public String paymentInfo(@PathVariable("id") Long id) { return restTemplate.getForObject(serverURL+"/payment/nacos/"+id,String.class); } }
- ⑥. 测试
- http://localhost:83/consumer/payment/nacos/13 (83访问9001/9002,轮询负载OK )
- nacos控制台