Springboot 项目集成 Nacos 实现服务注册发现与配置管理

开发 前端
我们通过使用 SpringBoot 项目集成 Nacos 来给大家演示一下是如何使用 Nacos 来实现服务发现和配置管理的。

[[393779]]

本文转载自微信公众号「Java极客技术」,作者鸭血粉丝。转载本文请联系Java极客技术公众号。  

Hello 大家好,我是阿粉,前面的文章给大家介绍了一下如何在本地搭建微服务环境下的服务注册中心和配置管理中心 Nacos,今天通过

我们通过使用 SpringBoot 项目集成 Nacos 来给大家演示一下是如何使用 Nacos 来实现服务发现和配置管理的。

启动 Nacos 服务

启动完本地搭建的 Nacos 服务后,我们可以看到,目前的服务管理下面的服务列表里面在三个命名空间下都没有服务,这是正常的,因为目前我们还没有服务接入Nacos。

Nacos 服务启动成功后,我们再创建两个 SpringBoot 项目,一个用于接入 Nacos 服务注册与发现和配置中心作为服务提供者 Producer,另一个只接入 Nacos的服务注册与发现,调用 Producer 获取配置中心的参数,我们叫做Consumer。

服务提供者 Producer

1.我们首先创建一个 SpringBoot 的项目,bootstrap.properties 文件内容如下:

  1. spring.application.name=producer 
  2.  
  3. #######################配置中心配置################################# 
  4. # 指定的命名空间,只会在对应的命名空间下查找对应的配置文件 
  5. spring.cloud.nacos.config.namespace=caeser-adsys-naming 
  6. spring.cloud.nacos.config.file-extension=properties 
  7. # 配置的分组名称 
  8. spring.cloud.nacos.config.group=TEST1 
  9. # 配置文件,数组形式,可以多个,依次递增 
  10. spring.cloud.nacos.config.ext-config[0].data-id=com.example.properties 
  11. spring.cloud.nacos.config.ext-config[0].group=TEST1 
  12. # 配置中心的地址 
  13. spring.cloud.nacos.config.server-addr=127.0.0.1:8848 
  14. #启用自动刷新对应的配置文件 
  15. spring.cloud.nacos.config.ext-config[0].refresh=true 
  16. ######################服务注册发现配置################################## 
  17.  
  18. # 服务集群名称 
  19. spring.cloud.nacos.discovery.cluster-name=TEST1_GROUP 
  20. # 服务注册中心的地址 
  21. spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 
  22. # 服务的命名空间 
  23. spring.cloud.nacos.discovery.namespace=caeser-adsys-naming 

2.application.properties 的文件内容如下,主要就是一个端口,其他配置根据情况自行添加或删除就好:

  1. # 服务启动的端口 
  2. server.port=8080 
  3. spring.main.allow-bean-definition-overriding=true 
  4. # tomcat 配置 
  5. server.tomcat.max-threads=500 
  6. spring.mvc.servlet.load-on-startup=1 
  7. spring.servlet.multipart.max-file-size=40MB 
  8. spring.servlet.multipart.max-request-size=100MB 
  9. # 日志配置 
  10. logging.level.root=info 
  11. logging.level.com.alibaba=error 
  12. logging.pattern.console=%clr{[%level]}{green} [%d{yyyy-MM-dd HH:mm:ss}] %clr{[${PID:-}]}{faint} %clr{[%thread]}{magenta} %clr{[%-40.40logger{80}:%line]}{cyan} %msg%n 

3.在启动类上面增加如下注解

  1. package com.ziyou.nacos.demo.producer; 
  2.  
  3. import org.springframework.boot.SpringApplication; 
  4. import org.springframework.boot.autoconfigure.SpringBootApplication; 
  5. import org.springframework.cache.annotation.EnableCaching; 
  6. import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 
  7.  
  8. @SpringBootApplication(scanBasePackages = "com.ziyou.nacos"
  9. @EnableDiscoveryClient 
  10. @EnableCaching 
  11. public class ProducerApplication { 
  12.  
  13.     public static void main(String[] args) { 
  14.         SpringApplication.run(ProducerApplication.class, args); 
  15.     } 

4.pom.xml 文件内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2.  
  3. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  4.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
  5.   <modelVersion>4.0.0</modelVersion> 
  6.  
  7.   <parent> 
  8.     <groupId>org.example</groupId> 
  9.     <artifactId>nacos-demo</artifactId> 
  10.     <version>1.0-SNAPSHOT</version> 
  11.   </parent> 
  12.  
  13.   <artifactId>producer</artifactId> 
  14.   <version>1.0-SNAPSHOT</version> 
  15.  
  16.   <name>producer Maven Webapp</name
  17.   <!-- FIXME change it to the project's website --> 
  18.   <url>http://www.example.com</url> 
  19.  
  20.   <properties> 
  21.     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
  22.     <maven.compiler.source>1.7</maven.compiler.source> 
  23.     <maven.compiler.target>1.7</maven.compiler.target> 
  24.     <spring.maven.plugin.version>2.2.2.RELEASE</spring.maven.plugin.version> 
  25.   </properties> 
  26.  
  27.   <dependencies> 
  28.     <!-- Spring Boot --> 
  29.     <dependency> 
  30.       <groupId>org.springframework.boot</groupId> 
  31.       <artifactId>spring-boot-starter</artifactId> 
  32.       <exclusions> 
  33.         <exclusion> 
  34.           <groupId>org.springframework.boot</groupId> 
  35.           <artifactId>spring-boot-starter-logging</artifactId> 
  36.         </exclusion> 
  37.       </exclusions> 
  38.     </dependency> 
  39.     <dependency> 
  40.       <groupId>org.springframework.boot</groupId> 
  41.       <artifactId>spring-boot-starter-log4j2</artifactId> 
  42.     </dependency> 
  43.     <dependency> 
  44.       <groupId>org.springframework.boot</groupId> 
  45.       <artifactId>spring-boot-starter-web</artifactId> 
  46.     </dependency> 
  47.  
  48.     <!-- nacos 配置中心 --> 
  49.     <dependency> 
  50.       <groupId>com.alibaba.cloud</groupId> 
  51.       <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> 
  52.     </dependency> 
  53.     <!-- nacos 注册发现 --> 
  54.     <dependency> 
  55.       <groupId>com.alibaba.cloud</groupId> 
  56.       <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> 
  57.     </dependency> 
  58.   </dependencies> 
  59.  
  60.   <build> 
  61.     <!--指定下面的目录为资源文件--> 
  62.     <resources> 
  63.       <!--设置自动替换--> 
  64.       <resource> 
  65.         <directory>src/main/resources</directory> 
  66.         <filtering>true</filtering> 
  67.         <includes> 
  68.           <include>**/**</include> 
  69.         </includes> 
  70.       </resource> 
  71.     </resources> 
  72.     <finalName>producer</finalName> 
  73.     <plugins> 
  74.       <plugin> 
  75.         <groupId>org.springframework.boot</groupId> 
  76.         <artifactId>spring-boot-maven-plugin</artifactId> 
  77.         <version>${spring.maven.plugin.version}</version> 
  78.         <executions> 
  79.           <execution> 
  80.             <goals> 
  81.               <goal>repackage</goal> 
  82.             </goals> 
  83.           </execution> 
  84.         </executions> 
  85.       </plugin> 
  86.     </plugins> 
  87.   </build> 
  88. </project> 

5.在 Producer 侧提供一个获取配置里面内容的接口,代码如下:

  1. package com.ziyou.nacos.demo.producer.controller; 
  2.  
  3. import com.ziyou.nacos.demo.producer.config.UserConfig; 
  4. import org.springframework.beans.factory.annotation.Autowired; 
  5. import org.springframework.web.bind.annotation.GetMapping; 
  6. import org.springframework.web.bind.annotation.RequestMapping; 
  7. import org.springframework.web.bind.annotation.RestController; 
  8.  
  9. /** 
  10.  * <br> 
  11.  * <b>Function:</b><br> 
  12.  * <b>Author:</b>@author ziyou<br> 
  13.  * <b>Date:</b>2021-04-11 19:59<br> 
  14.  * <b>Desc:</b>无<br> 
  15.  */ 
  16. @RestController 
  17. @RequestMapping(value = "producer"
  18. public class ProducerController { 
  19.  
  20.     private UserConfig userConfig; 
  21.  
  22.     @GetMapping("/getUsername"
  23.     private String getUsername() { 
  24.         String result = userConfig.getUsername() + "-" + userConfig.getPassword(); 
  25.         System.out.println(result); 
  26.         return result; 
  27.     } 
  28.  
  29.     @Autowired 
  30.     public void setUserConfig(UserConfig userConfig) { 
  31.         this.userConfig = userConfig; 
  32.     } 
  1. package com.ziyou.nacos.demo.producer.config; 
  2.  
  3. import org.springframework.beans.factory.annotation.Value; 
  4. import org.springframework.cloud.context.config.annotation.RefreshScope; 
  5. import org.springframework.stereotype.Component; 
  6.  
  7. /** 
  8.  * <br> 
  9.  * <b>Function:</b><br> 
  10.  * <b>Author:</b>@author ziyou<br> 
  11.  * <b>Date:</b>2021-04-11 20:39<br> 
  12.  * <b>Desc:</b>无<br> 
  13.  */ 
  14. @RefreshScope 
  15. @Component 
  16. public class UserConfig { 
  17.     @Value("${username}"
  18.     private String username; 
  19.     @Value("${password}"
  20.     private String password
  21.  
  22.     public String getUsername() { 
  23.         return username; 
  24.     } 
  25.  
  26.     public void setUsername(String username) { 
  27.         this.username = username; 
  28.     } 
  29.  
  30.     public String getPassword() { 
  31.         return password
  32.     } 
  33.  
  34.     public void setPassword(String password) { 
  35.         this.password = password
  36.     } 

6.启动 Producer,并且手动调用接口,启动 Producer 过后,我们在 Nacos 的服务注册列表可以看如下所示的内容,在 test1 的命名空间下,已经有了我们创建的 Producer 服务。

7.通过手动调用 Producer 的接口 http://127.0.0.1:8080/producer/getUsername 显示如下内容

并且我们看下此时 Nacos 的配置中心里面配置文件com.example.properties 里面的内容正是这个,这个时候我们手动把配置里面password 参数的值改成JavaGeek666,再次访问接口,我们会发现接口的输出也自动改变了。

修改配置内容如下:

再次访问结果如下:

服务调用者 Consumer

前面我们已经完成了Producer 的服务注册与配置动态生效的功能,这个时候基本已经可以使用了,不过我们还需要更进一步通过 Nacos 来实现服务发现,接下来我们创建 Consumer 的 SpringBoot 的项目,配置文件和pom.xml 文件基本一致,只要修改端口以及对应地方,下面贴一下不一样的地方

1.boostrap.properties 内容如下,因为这里我们只调用Producer 的接口,不需要接入 Nacos 的配置中心,所以这里只配置发服务注册与发现

  1. spring.application.name=consumer 
  2.  
  3. ######################服务注册发现配置################################## 
  4. spring.cloud.nacos.discovery.cluster-name=TEST1_GROUP 
  5. spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 
  6. spring.cloud.nacos.discovery.namespace=caeser-adsys-naming 

2.启动类,配置上 feignClient 需要扫描的包路径

  1. package com.ziyou.nacos.demo.consumer; 
  2.  
  3. import org.springframework.boot.SpringApplication; 
  4. import org.springframework.boot.autoconfigure.SpringBootApplication; 
  5. import org.springframework.cache.annotation.EnableCaching; 
  6. import org.springframework.cloud.openfeign.EnableFeignClients; 
  7.  
  8. /** 
  9.  * <br> 
  10.  * <b>Function:</b><br> 
  11.  * <b>Author:</b>@author ziyou<br> 
  12.  * <b>Date:</b>2021-04-11 17:07<br> 
  13.  * <b>Desc:</b>无<br> 
  14.  */ 
  15. @SpringBootApplication(scanBasePackages = "com.ziyou.nacos"
  16. @EnableFeignClients(basePackages = {"com.ziyou.nacos.demo.consumer.rpc"}) 
  17. @EnableCaching 
  18. public class ConsumerApplication { 
  19.     public static void main(String[] args) { 
  20.         SpringApplication.run(ConsumerApplication.class, args); 
  21.     } 

3.编写调用 Producer 的接口,FeignClient 里面的 value 就是 Producer 的应用名称

  1. package com.ziyou.nacos.demo.consumer.rpc; 
  2.  
  3. import org.springframework.cloud.openfeign.FeignClient; 
  4. import org.springframework.stereotype.Component; 
  5. import org.springframework.web.bind.annotation.GetMapping; 
  6.  
  7. /** 
  8.  * <br> 
  9.  * <b>Function:</b><br> 
  10.  * <b>Author:</b>@author ziyou<br> 
  11.  * <b>Date:</b>2021-04-11 20:01<br> 
  12.  * <b>Desc:</b>无<br> 
  13.  */ 
  14. @FeignClient(value = "producer"
  15. @Component 
  16. public interface IProducerFeign { 
  17.     /** 
  18.      * 获取生产者名称接口 
  19.      * 
  20.      * @return 
  21.      */ 
  22.     @GetMapping("/producer/getUsername"
  23.     String getUsername(); 
  24.  
  1. package com.ziyou.nacos.demo.consumer.controller; 
  2.  
  3. import com.ziyou.nacos.demo.consumer.rpc.IProducerFeign; 
  4. import org.springframework.beans.factory.annotation.Autowired; 
  5. import org.springframework.web.bind.annotation.GetMapping; 
  6. import org.springframework.web.bind.annotation.RequestMapping; 
  7. import org.springframework.web.bind.annotation.RestController; 
  8.  
  9. /** 
  10.  * <br> 
  11.  * <b>Function:</b><br> 
  12.  * <b>Author:</b>@author ziyou<br> 
  13.  * <b>Date:</b>2021-04-11 19:59<br> 
  14.  * <b>Desc:</b>无<br> 
  15.  */ 
  16. @RestController 
  17. @RequestMapping(value = "consumer"
  18. public class TestNacosController { 
  19.  
  20.     private IProducerFeign iProducerFeign; 
  21.  
  22.     @GetMapping("/testNacos"
  23.     private String testNacos() { 
  24.         return iProducerFeign.getUsername(); 
  25.     } 
  26.  
  27.     @Autowired 
  28.     public void setiProducerFeign(IProducerFeign iProducerFeign) { 
  29.         this.iProducerFeign = iProducerFeign; 
  30.     } 

4.启动Consumer,我们可以看到在 Nacos 如下图所示

5.调用 Consumer 的接口consumer/testNacos,结果如下图所示,同样的如果此时更改了 Nacos 配置文件中的内容,Consumer 这边也是可以实时更新的,感兴趣的小伙伴可以自己试试。

 

今天主要给大家介绍了一下如何通过 SpringBoot 项目来接入 Naocs 实现服务注册与发现,以及配置管理和动态刷新,相关的代码已经上传到 GitHub 了。

 

责任编辑:武晓燕 来源: Java极客技术
相关推荐

2022-02-07 07:10:32

服务注册功能

2022-02-09 07:03:01

SpringNacos服务注册

2022-04-26 05:36:42

服务治理模式

2023-12-07 08:07:10

2023-04-27 08:18:25

GitLab开源

2021-04-20 17:20:59

SpringColud EurekaNetflix开发

2015-12-25 11:00:52

Zookeeper的Python

2022-06-08 10:58:00

服务配置Nacos

2022-06-13 09:58:06

NacosSpring

2021-07-12 08:00:21

Nacos 服务注册源码分析

2023-08-03 08:51:07

2023-05-30 07:50:56

项目管理权限

2023-11-29 16:21:30

Kubernetes服务注册

2022-01-16 23:10:40

语言服务注册

2009-03-03 17:17:52

环境配置软件开发

2022-07-01 08:36:44

流编排主流框架

2009-03-25 09:52:00

虚拟网络VLAN配置

2022-07-07 10:43:58

安全配置管理SCM

2020-08-26 07:37:25

Nacos微服务SpringBoot

2023-05-31 07:54:11

点赞
收藏

51CTO技术栈公众号