Springboot 項(xiàng)目集成 Nacos 實(shí)現(xiàn)服務(wù)注冊(cè)發(fā)現(xiàn)與配置管理
本文轉(zhuǎn)載自微信公眾號(hào)「Java極客技術(shù)」,作者鴨血粉絲。轉(zhuǎn)載本文請(qǐng)聯(lián)系Java極客技術(shù)公眾號(hào)。
Hello 大家好,我是阿粉,前面的文章給大家介紹了一下如何在本地搭建微服務(wù)環(huán)境下的服務(wù)注冊(cè)中心和配置管理中心 Nacos,今天通過(guò)
我們通過(guò)使用 SpringBoot 項(xiàng)目集成 Nacos 來(lái)給大家演示一下是如何使用 Nacos 來(lái)實(shí)現(xiàn)服務(wù)發(fā)現(xiàn)和配置管理的。
啟動(dòng) Nacos 服務(wù)
啟動(dòng)完本地搭建的 Nacos 服務(wù)后,我們可以看到,目前的服務(wù)管理下面的服務(wù)列表里面在三個(gè)命名空間下都沒(méi)有服務(wù),這是正常的,因?yàn)槟壳拔覀冞€沒(méi)有服務(wù)接入Nacos。
Nacos 服務(wù)啟動(dòng)成功后,我們?cè)賱?chuàng)建兩個(gè) SpringBoot 項(xiàng)目,一個(gè)用于接入 Nacos 服務(wù)注冊(cè)與發(fā)現(xiàn)和配置中心作為服務(wù)提供者 Producer,另一個(gè)只接入 Nacos的服務(wù)注冊(cè)與發(fā)現(xiàn),調(diào)用 Producer 獲取配置中心的參數(shù),我們叫做Consumer。
服務(wù)提供者 Producer
1.我們首先創(chuàng)建一個(gè) SpringBoot 的項(xiàng)目,bootstrap.properties 文件內(nèi)容如下:
- spring.application.name=producer
- #######################配置中心配置#################################
- # 指定的命名空間,只會(huì)在對(duì)應(yīng)的命名空間下查找對(duì)應(yīng)的配置文件
- spring.cloud.nacos.config.namespace=caeser-adsys-naming
- spring.cloud.nacos.config.file-extension=properties
- # 配置的分組名稱
- spring.cloud.nacos.config.group=TEST1
- # 配置文件,數(shù)組形式,可以多個(gè),依次遞增
- spring.cloud.nacos.config.ext-config[0].data-id=com.example.properties
- spring.cloud.nacos.config.ext-config[0].group=TEST1
- # 配置中心的地址
- spring.cloud.nacos.config.server-addr=127.0.0.1:8848
- #啟用自動(dòng)刷新對(duì)應(yīng)的配置文件
- spring.cloud.nacos.config.ext-config[0].refresh=true
- ######################服務(wù)注冊(cè)發(fā)現(xiàn)配置##################################
- # 服務(wù)集群名稱
- spring.cloud.nacos.discovery.cluster-name=TEST1_GROUP
- # 服務(wù)注冊(cè)中心的地址
- spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
- # 服務(wù)的命名空間
- spring.cloud.nacos.discovery.namespace=caeser-adsys-naming
2.application.properties 的文件內(nèi)容如下,主要就是一個(gè)端口,其他配置根據(jù)情況自行添加或刪除就好:
- # 服務(wù)啟動(dòng)的端口
- server.port=8080
- spring.main.allow-bean-definition-overriding=true
- # tomcat 配置
- server.tomcat.max-threads=500
- spring.mvc.servlet.load-on-startup=1
- spring.servlet.multipart.max-file-size=40MB
- spring.servlet.multipart.max-request-size=100MB
- # 日志配置
- logging.level.root=info
- logging.level.com.alibaba=error
- 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.在啟動(dòng)類上面增加如下注解
- package com.ziyou.nacos.demo.producer;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.cache.annotation.EnableCaching;
- import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
- @SpringBootApplication(scanBasePackages = "com.ziyou.nacos")
- @EnableDiscoveryClient
- @EnableCaching
- public class ProducerApplication {
- public static void main(String[] args) {
- SpringApplication.run(ProducerApplication.class, args);
- }
- }
4.pom.xml 文件內(nèi)容如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.example</groupId>
- <artifactId>nacos-demo</artifactId>
- <version>1.0-SNAPSHOT</version>
- </parent>
- <artifactId>producer</artifactId>
- <version>1.0-SNAPSHOT</version>
- <name>producer Maven Webapp</name>
- <!-- FIXME change it to the project's website -->
- <url>http://www.example.com</url>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <maven.compiler.source>1.7</maven.compiler.source>
- <maven.compiler.target>1.7</maven.compiler.target>
- <spring.maven.plugin.version>2.2.2.RELEASE</spring.maven.plugin.version>
- </properties>
- <dependencies>
- <!-- Spring Boot -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter</artifactId>
- <exclusions>
- <exclusion>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-logging</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-log4j2</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <!-- nacos 配置中心 -->
- <dependency>
- <groupId>com.alibaba.cloud</groupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
- </dependency>
- <!-- nacos 注冊(cè)發(fā)現(xiàn) -->
- <dependency>
- <groupId>com.alibaba.cloud</groupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
- </dependency>
- </dependencies>
- <build>
- <!--指定下面的目錄為資源文件-->
- <resources>
- <!--設(shè)置自動(dòng)替換-->
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- <includes>
- <include>**/**</include>
- </includes>
- </resource>
- </resources>
- <finalName>producer</finalName>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <version>${spring.maven.plugin.version}</version>
- <executions>
- <execution>
- <goals>
- <goal>repackage</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </project>
5.在 Producer 側(cè)提供一個(gè)獲取配置里面內(nèi)容的接口,代碼如下:
- package com.ziyou.nacos.demo.producer.controller;
- import com.ziyou.nacos.demo.producer.config.UserConfig;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- /**
- * <br>
- * <b>Function:</b><br>
- * <b>Author:</b>@author ziyou<br>
- * <b>Date:</b>2021-04-11 19:59<br>
- * <b>Desc:</b>無(wú)<br>
- */
- @RestController
- @RequestMapping(value = "producer")
- public class ProducerController {
- private UserConfig userConfig;
- @GetMapping("/getUsername")
- private String getUsername() {
- String result = userConfig.getUsername() + "-" + userConfig.getPassword();
- System.out.println(result);
- return result;
- }
- @Autowired
- public void setUserConfig(UserConfig userConfig) {
- this.userConfig = userConfig;
- }
- }
- package com.ziyou.nacos.demo.producer.config;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.cloud.context.config.annotation.RefreshScope;
- import org.springframework.stereotype.Component;
- /**
- * <br>
- * <b>Function:</b><br>
- * <b>Author:</b>@author ziyou<br>
- * <b>Date:</b>2021-04-11 20:39<br>
- * <b>Desc:</b>無(wú)<br>
- */
- @RefreshScope
- @Component
- public class UserConfig {
- @Value("${username}")
- private String username;
- @Value("${password}")
- private String password;
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
6.啟動(dòng) Producer,并且手動(dòng)調(diào)用接口,啟動(dòng) Producer 過(guò)后,我們?cè)?Nacos 的服務(wù)注冊(cè)列表可以看如下所示的內(nèi)容,在 test1 的命名空間下,已經(jīng)有了我們創(chuàng)建的 Producer 服務(wù)。
7.通過(guò)手動(dòng)調(diào)用 Producer 的接口 http://127.0.0.1:8080/producer/getUsername 顯示如下內(nèi)容
并且我們看下此時(shí) Nacos 的配置中心里面配置文件com.example.properties 里面的內(nèi)容正是這個(gè),這個(gè)時(shí)候我們手動(dòng)把配置里面password 參數(shù)的值改成JavaGeek666,再次訪問(wèn)接口,我們會(huì)發(fā)現(xiàn)接口的輸出也自動(dòng)改變了。
修改配置內(nèi)容如下:
再次訪問(wèn)結(jié)果如下:
服務(wù)調(diào)用者 Consumer
前面我們已經(jīng)完成了Producer 的服務(wù)注冊(cè)與配置動(dòng)態(tài)生效的功能,這個(gè)時(shí)候基本已經(jīng)可以使用了,不過(guò)我們還需要更進(jìn)一步通過(guò) Nacos 來(lái)實(shí)現(xiàn)服務(wù)發(fā)現(xiàn),接下來(lái)我們創(chuàng)建 Consumer 的 SpringBoot 的項(xiàng)目,配置文件和pom.xml 文件基本一致,只要修改端口以及對(duì)應(yīng)地方,下面貼一下不一樣的地方
1.boostrap.properties 內(nèi)容如下,因?yàn)檫@里我們只調(diào)用Producer 的接口,不需要接入 Nacos 的配置中心,所以這里只配置發(fā)服務(wù)注冊(cè)與發(fā)現(xiàn)
- spring.application.name=consumer
- ######################服務(wù)注冊(cè)發(fā)現(xiàn)配置##################################
- spring.cloud.nacos.discovery.cluster-name=TEST1_GROUP
- spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
- spring.cloud.nacos.discovery.namespace=caeser-adsys-naming
2.啟動(dòng)類,配置上 feignClient 需要掃描的包路徑
- package com.ziyou.nacos.demo.consumer;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.cache.annotation.EnableCaching;
- import org.springframework.cloud.openfeign.EnableFeignClients;
- /**
- * <br>
- * <b>Function:</b><br>
- * <b>Author:</b>@author ziyou<br>
- * <b>Date:</b>2021-04-11 17:07<br>
- * <b>Desc:</b>無(wú)<br>
- */
- @SpringBootApplication(scanBasePackages = "com.ziyou.nacos")
- @EnableFeignClients(basePackages = {"com.ziyou.nacos.demo.consumer.rpc"})
- @EnableCaching
- public class ConsumerApplication {
- public static void main(String[] args) {
- SpringApplication.run(ConsumerApplication.class, args);
- }
- }
3.編寫調(diào)用 Producer 的接口,F(xiàn)eignClient 里面的 value 就是 Producer 的應(yīng)用名稱
- package com.ziyou.nacos.demo.consumer.rpc;
- import org.springframework.cloud.openfeign.FeignClient;
- import org.springframework.stereotype.Component;
- import org.springframework.web.bind.annotation.GetMapping;
- /**
- * <br>
- * <b>Function:</b><br>
- * <b>Author:</b>@author ziyou<br>
- * <b>Date:</b>2021-04-11 20:01<br>
- * <b>Desc:</b>無(wú)<br>
- */
- @FeignClient(value = "producer")
- @Component
- public interface IProducerFeign {
- /**
- * 獲取生產(chǎn)者名稱接口
- *
- * @return
- */
- @GetMapping("/producer/getUsername")
- String getUsername();
- }
- package com.ziyou.nacos.demo.consumer.controller;
- import com.ziyou.nacos.demo.consumer.rpc.IProducerFeign;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- /**
- * <br>
- * <b>Function:</b><br>
- * <b>Author:</b>@author ziyou<br>
- * <b>Date:</b>2021-04-11 19:59<br>
- * <b>Desc:</b>無(wú)<br>
- */
- @RestController
- @RequestMapping(value = "consumer")
- public class TestNacosController {
- private IProducerFeign iProducerFeign;
- @GetMapping("/testNacos")
- private String testNacos() {
- return iProducerFeign.getUsername();
- }
- @Autowired
- public void setiProducerFeign(IProducerFeign iProducerFeign) {
- this.iProducerFeign = iProducerFeign;
- }
- }
4.啟動(dòng)Consumer,我們可以看到在 Nacos 如下圖所示
5.調(diào)用 Consumer 的接口consumer/testNacos,結(jié)果如下圖所示,同樣的如果此時(shí)更改了 Nacos 配置文件中的內(nèi)容,Consumer 這邊也是可以實(shí)時(shí)更新的,感興趣的小伙伴可以自己試試。
今天主要給大家介紹了一下如何通過(guò) SpringBoot 項(xiàng)目來(lái)接入 Naocs 實(shí)現(xiàn)服務(wù)注冊(cè)與發(fā)現(xiàn),以及配置管理和動(dòng)態(tài)刷新,相關(guān)的代碼已經(jīng)上傳到 GitHub 了。