Nacos作为服务注册中心简单示例

一、服务注册与发现场景

主要包含两个服务:

  • zhshl-order服务: 作为服务消费者
  • zhsl-stock服务: 作为服务提供者

当我们启用服务发现的时候,需要进行的操作主要有三步

0、前置条件,需要先搭建好一个nacas服务,可以是一个集群或者是单个nacos服务。可以参考https://nacos.io/zh-cn/docs/quick-start.html,

示例中使用需要使用nacos1.4.2版本匹配。具体配置关系可以参考:https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E

1、添加maven依赖

     <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
     </dependency>

2、配置服务提供者,将服务注册到nacos中,后续通过

2.1 在bootstrap.yml的配置文件中配置nacos的地址
spring:
  cloud:
    nacos:
      discovery:
        service: zhshl-stock
        server-addr: localhost:8848

server:
  port: 8081
2.2 通过 Spring Cloud 原生注解 @EnableDiscoveryClient 开启服务注册发现功能:
@SpringBootApplication
@EnableDiscoveryClient
public class ZhslStockApplication {
    
    

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

@RestController
public class StockController {
    
    
    @Value("${server.port}")
    private String port;

    @GetMapping("/stock/reduce/{productId}")
    public String reduce(@PathVariable Integer productId) {
    
    
        System.out.println("减库存成功");
        return "减库存成功,响应的是: " + port;
    }
}

3、配置消费者,消费通过nacos的服务发现功能,从nacos中获取到对应的服务提供者的具体实例来进行调用

3.1、服务消费者对应的配置信息:
spring:
  cloud:
    nacos:
      discovery:
        service: zhshl-stock
        server-addr: localhost:8848

server:
  port: 18082
3.2、 消费者的配置启用服务发现
@SpringBootApplication
@EnableDiscoveryClient
public class ZhshlOrderApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(ZhshlOrderApplication.class, args);
    }
}
@Configuration
public class AppConfig {
    
    
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Bean
    //@LoadBalanced
    public RestTemplate restTemplate(){
    
    
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(Collections.singletonList(new LoadBalancerInterceptor(loadBalancerClient)));
        return restTemplate;
    }
}
@Slf4j
@RestController
public class OrderController {
    
    
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/order/create")
    public String createOrder(Integer productId, Integer userId) {
    
    

        String result = restTemplate.getForObject("http://zhshl-stock/stock/reduce/" + productId, String.class);
        return "下单成功,库存响应: " + result;
    }
}

4、启动服务提供者(zhsl-stock)和服务消费者(zhshl-order)

4.1、两个服务启动后,可以在nacos的控制平台上看到如下信息

在这里插入图片描述

4.2 在浏览器上输入http://localhost:8082/order/create?productId=10,然后可以到如下的输出:

下单成功,库存响应: 减库存成功,响应的是: 18082
在这里插入图片描述
文章使用到的源码请见:https://github.com/zhang1github2test/nacos-zhshl-parent/tree/master

猜你喜欢

转载自blog.csdn.net/zhangshenglu1/article/details/131035271