• SpringBoot使用Nacos进行服务注册发现与配置管理


    背景

    公司开发用微服务SpringCloud生态,采用nacos进行服务注册和管理,最近希望通过自己搭建一套,体会nacos技术栈在其中的作用及原理。

    简介

    nacos中文网站

    内容来自官网:

    Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service的首字母简称,一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。

    Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。

    Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。 Nacos 是构建以“服务”为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施。

    Nacos 地图

    • 特性大图:要从功能特性,非功能特性,全面介绍我们要解的问题域的特性诉求
    • 架构大图:通过清晰架构,让您快速进入 Nacos 世界
    • 业务大图:利用当前特性可以支持的业务场景,及其最佳实践
    • 生态大图:系统梳理 Nacos 和主流技术生态的关系
    • 优势大图:展示 Nacos 核心竞争力
    • 战略大图:要从战略到战术层面讲 Nacos 的宏观优势

    Nacos服务部署

    参见我之前的文章:

    Windows下Nacos安装

    部署成果之后登录页面如下: 

    SpirngBoot应用使用Nacos作为注册中心

    SpringBoot应用使用Nacos作为注册中心需要引入依赖nacos-discovery-spring-boot-starter,依赖的版本为0.2.4,对应于SpringBoot的版本为2.0.3.RELEASE,引入如下依赖:

    1. <dependencyManagement>
    2. <dependencies>
    3. <dependency>
    4. <groupId>org.springframework.bootgroupId>
    5. <artifactId>spring-boot-dependenciesartifactId>
    6. <version>2.0.3.RELEASEversion>
    7. <type>pomtype>
    8. <scope>importscope>
    9. dependency>
    10. dependencies>
    11. dependencyManagement>
    12. <dependencies>
    13. <dependency>
    14. <groupId>org.springframework.bootgroupId>
    15. <artifactId>spring-boot-starter-webartifactId>
    16. dependency>
    17. <dependency>
    18. <groupId>com.alibaba.bootgroupId>
    19. <artifactId>nacos-discovery-spring-boot-starterartifactId>
    20. <version>0.2.4version>
    21. dependency>
    22. dependencies>

    下面以一个简单的生产者和消费者服务的例子进行演示:

    生产者:

    为了方便起见,把控制器、服务注册的代码都写在启动类ProvideApplication中:

    1. import com.alibaba.nacos.api.annotation.NacosInjected;
    2. import com.alibaba.nacos.api.naming.NamingService;
    3. import org.springframework.beans.factory.annotation.Value;
    4. import org.springframework.boot.CommandLineRunner;
    5. import org.springframework.boot.SpringApplication;
    6. import org.springframework.boot.autoconfigure.SpringBootApplication;
    7. import org.springframework.web.bind.annotation.GetMapping;
    8. import org.springframework.web.bind.annotation.RequestParam;
    9. import org.springframework.web.bind.annotation.RestController;
    10. /**
    11. * @author ase
    12. * @version v1.0
    13. * @description
    14. * @since 2022/8/21 22:46
    15. */
    16. @RestController
    17. @SpringBootApplication(scanBasePackages = "com.springboot.nacosdemo.provide")
    18. public class ProvideApplication implements CommandLineRunner {
    19. @NacosInjected
    20. private NamingService namingService;
    21. @Value("${spring.application.name}")
    22. private String applicationName;
    23. @Value("${server.port}")
    24. private Integer serverPort;
    25. public static void main(String[] args) {
    26. SpringApplication.run(ProvideApplication.class, args);
    27. }
    28. @GetMapping(path = "/hello")
    29. public String hello(@RequestParam(name = "name") String name) {
    30. return String.format("%s say hello!", name);
    31. }
    32. @Override
    33. public void run(String... args) throws Exception {
    34. // 通过Naming服务注册实例到注册中心
    35. namingService.registerInstance(applicationName, "127.0.0.1", serverPort);
    36. }
    37. }

    配置文件application-provide.properties内容如下:

    1. spring.application.name=provide-service
    2. server.port=9092
    3. nacos.discovery.server-addr=127.0.0.1:8848

    使用spring.profiles.active=provide启动ProvideApplication

    启动成功后用浏览器打开Nacos-Console

    暂时可知服务的提供方已经注册成功。 

    接着编写服务的消费方代码,引入的最小依赖和服务提供方完全一致,编写启动类ConsumeApplication如下:

    1. import com.alibaba.nacos.api.annotation.NacosInjected;
    2. import com.alibaba.nacos.api.naming.NamingService;
    3. import com.alibaba.nacos.api.naming.pojo.Instance;
    4. import org.springframework.beans.factory.annotation.Value;
    5. import org.springframework.boot.CommandLineRunner;
    6. import org.springframework.boot.SpringApplication;
    7. import org.springframework.boot.autoconfigure.SpringBootApplication;
    8. import org.springframework.web.client.RestTemplate;
    9. /**
    10. * @author ase
    11. * @version v1.0
    12. * @description
    13. * @since 2022/8/21 22:46
    14. */
    15. @SpringBootApplication(scanBasePackages = "com.springboot.nacosdemo.consume")
    16. public class ConsumeApplication implements CommandLineRunner {
    17. @NacosInjected
    18. private NamingService namingService;
    19. @Value("${spring.application.name}")
    20. private String applicationName;
    21. @Value("${server.port}")
    22. private Integer serverPort;
    23. public static void main(String[] args) {
    24. SpringApplication.run(ConsumeApplication.class, args);
    25. }
    26. @Override
    27. public void run(String... args) throws Exception {
    28. // 通过Naming服务注册实例到注册中心
    29. namingService.registerInstance(applicationName, "127.0.0.1", serverPort);
    30. // 根据服务名从注册中心获取一个健康的服务实例
    31. Instance instance = namingService.selectOneHealthyInstance("provide-service");
    32. // 这里只是为了方便才新建RestTemplate实例
    33. RestTemplate template = new RestTemplate();
    34. String url = String.format("http://%s:%d/hello?name=throwable", instance.getIp(), instance.getPort());
    35. String result = template.getForObject(url, String.class);
    36. System.out.println(String.format("请求URL:%s,响应结果:%s", url, result));
    37. }
    38. }

    配置文件application-provide.properties内容如下:

    1. spring.application.name=consume-service
    2. server.port=9091
    3. nacos.discovery.server-addr=127.0.0.1:8848

    使用spring.profiles.active=consume启动ConsumeApplication

     启动成功后用浏览器打开Nacos-Console

     查看consumer服务控制台输出:

     

    SpirngBoot应用使用Nacos管理配置

    如果使用Nacos进行配置管理,则需要引入nacos-config-spring-boot-starter依赖:

    1. <dependencyManagement>
    2. <dependencies>
    3. <dependency>
    4. <groupId>org.springframework.bootgroupId>
    5. <artifactId>spring-boot-dependenciesartifactId>
    6. <version>2.0.3.RELEASEversion>
    7. <type>pomtype>
    8. <scope>importscope>
    9. dependency>
    10. dependencies>
    11. dependencyManagement>
    12. <dependencies>
    13. <dependency>
    14. <groupId>org.springframework.bootgroupId>
    15. <artifactId>spring-boot-starter-webartifactId>
    16. dependency>
    17. <dependency>
    18. <groupId>com.alibaba.bootgroupId>
    19. <artifactId>nacos-config-spring-boot-starterartifactId>
    20. <version>0.2.4version>
    21. dependency>
    22. dependencies>

    新建一个启动类ConfigApplication如下:

    1. import com.alibaba.nacos.api.config.annotation.NacosValue;
    2. import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
    3. import org.springframework.boot.SpringApplication;
    4. import org.springframework.boot.autoconfigure.SpringBootApplication;
    5. import org.springframework.web.bind.annotation.GetMapping;
    6. import org.springframework.web.bind.annotation.RestController;
    7. /**
    8. * @author ase
    9. * @version v1.0
    10. * @description
    11. * @since 2022/8/21 22:46
    12. */
    13. @RestController
    14. @NacosPropertySource(dataId = "example", autoRefreshed = true)
    15. @SpringBootApplication(scanBasePackages = "com.springboot.nacosdemo.config")
    16. public class ConfigApplication {
    17. @NacosValue(value = "${counter:0}", autoRefreshed = true)
    18. public Long counter;
    19. public static void main(String[] args) {
    20. SpringApplication.run(ConfigApplication.class, args);
    21. }
    22. @GetMapping(path = "/get")
    23. public String get() {
    24. return String.format("Counter value:%d", counter);
    25. }
    26. }

    代码中定义了一个长整型的计数器,设置了autoRefreshed(自动刷新)为true

    新建一个配置文件application-config.properties

    1. spring.application.name=config-service
    2. server.port=9093
    3. nacos.config.server-addr=127.0.0.1:8848

    使用spring.profiles.active=config启动ConfigApplication,启动成功后通过CURL调用下面的接口:

    1. curl -X GET http://127.0.0.1:9093/get
    2. Counter value:0

    接着通过Nacos-Console添加一个DataID为example的配置:

     点击发布按钮后再次调用接口:

     

    1. curl -X GET http://127.0.0.1:9093/get
    2. Counter value:54321

    可见计数器的值已经动态刷新。

    小结

    本文只是简单介绍了SpringBoot中使用Nacos作为注册中心以及进行配置管理。nacos在多服务下的配置使用及其他知识,未来将逐步深入探究。

     

    参考:

    SpringBoot使用Nacos进行服务注册发现与配置管理

     

  • 相关阅读:
    laravel使用rabbitmq队列
    STM32 CortexM4 主控板触摸屏保姆级别总结
    弘辽科技:拼多多选品的方式有哪些?有什么选品技巧?
    006_Makefile Study(1)
    Python基础知识篇(自学必备)
    深入理解 pytest.main():Python 测试框架的核心功能解析
    C/C++ 时间知识总结
    支付宝内部打开h5页面报错
    也许是最客观、全面的比较 Rust 与 Go:都想把 Rust 也学一下
    【Vivado】Xilinx UG994 Addressing for Block Designs
  • 原文地址:https://blog.csdn.net/akenseren/article/details/126456862