springcloud alibaba-消费者模块注册到nacos
1. 新建消费者模块
2. 添加依赖(参照生产者模块,nacos 的依赖都是一样的)
3. 添加配置
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
4. 主启动
@EnableDiscoveryClient @SpringBootApplication public class OrderNacos83Application { public static void main(String[] args) { SpringApplication.run(OrderNacos83Application.class, args); } }
5. 业务类
@Configuration public class ApplicationContextConfig { @Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); } }
对了,nacos具备负载均衡的能力,底层是使用的Ribbon
@RestController public class Order83Controller { @Resource private RestTemplate restTemplate; @Value("${service-url.nacos-user-service}") private String serverURL; @GetMapping("/consumer/payment/nacos/{id}") public String paymentInfo(@PathVariable("id") Long id) { return restTemplate.getForObject(serverURL + "/payment/nacos/" + id, String.class); } }
6. 测试。http://localhost:83/consumer/payment/nacos/2