前情提要
Spring Cloud Alibaba Github

安装Nacos服务器

Docker安装

  1. docker search nacos
  2. docker pull nacos/nacos-server
  3. docker run --env MODE=standalone --name nacos -d -p 8848:8848 nacos/nacos-server

访问http://localhost:8848/nacos即可

生产者/消费者

生产者与消费者代码几乎相同

添加依赖

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.2.10.BUILD-SNAPSHOT</version>
  5. <relativePath/> <!-- lookup parent from repository -->
  6. </parent>
  7. <dependency>
  8. <groupId>com.alibaba.cloud</groupId>
  9. <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
  10. </dependency>

修改配置文件

  1. # application.yml
  2. server:
  3. port: 8001
  4. spring:
  5. application:
  6. name: nacos-provider
  7. cloud:
  8. nacos:
  9. discovery:
  10. server-addr: localhost:8848 # nacos注册中心

消费者调用生产者

nacos内置了ribbon,因此调用方式与ribbon相同,下面是nacos提供的调用模板:

  1. @SpringBootApplication
  2. @EnableDiscoveryClient
  3. public class NacosConsumerApplication {
  4. @LoadBalanced
  5. @Bean
  6. public RestTemplate restTemplate() {
  7. return new RestTemplate();
  8. }
  9. public static void main(String[] args) {
  10. SpringApplication.run(NacosConsumerApplication.class, args);
  11. }
  12. @RestController
  13. public class TestController {
  14. private final RestTemplate restTemplate;
  15. @Autowired
  16. public TestController(RestTemplate restTemplate) {this.restTemplate = restTemplate;}
  17. @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
  18. public String echo(@PathVariable String str) {
  19. return restTemplate.getForObject("http://service-provider/echo/" + str, String.class);
  20. }
  21. }
  22. }

源码访问
nacos-consumer
nacos-provider