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

简介: Hello 大家好,我是阿粉,前面的文章给大家介绍了一下如何在本地搭建微服务环境下的服务注册中心和配置管理中心 Nacos,今天通过我们通过使用 SpringBoot 项目集成 Nacos 来给大家演示一下是如何使用 Nacos 来实现服务发现和配置管理的。

启动 Nacos 服务

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

74.jpg

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

服务提供者 Producer

  1. 我们首先创建一个 SpringBoot 的项目,bootstrap.properties 文件内容如下:
spring.application.name=producer
#######################配置中心配置#################################
# 指定的命名空间,只会在对应的命名空间下查找对应的配置文件
spring.cloud.nacos.config.namespace=caeser-adsys-naming
spring.cloud.nacos.config.file-extension=properties
# 配置的分组名称
spring.cloud.nacos.config.group=TEST1
# 配置文件,数组形式,可以多个,依次递增
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
#启用自动刷新对应的配置文件
spring.cloud.nacos.config.ext-config[0].refresh=true
######################服务注册发现配置##################################
# 服务集群名称
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
  1. application.properties 的文件内容如下,主要就是一个端口,其他配置根据情况自行添加或删除就好:
# 服务启动的端口
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
  1. 在启动类上面增加如下注解
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);
    }
}
  1. pom.xml 文件内容如下:
<?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 注册发现 -->
    <dependency>
      <groupId>com.alibaba.cloud</groupId>
      <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
  </dependencies>
  <build>
    <!--指定下面的目录为资源文件-->
    <resources>
      <!--设置自动替换-->
      <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>
  1. Producer 侧提供一个获取配置里面内容的接口,代码如下:
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>无<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>无<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;
    }
}
相关文章
|
10月前
|
JSON 分布式计算 大数据
springboot项目集成大数据第三方dolphinscheduler调度器
springboot项目集成大数据第三方dolphinscheduler调度器
649 3
|
10月前
|
Java 关系型数据库 数据库连接
Spring Boot项目集成MyBatis Plus操作PostgreSQL全解析
集成 Spring Boot、PostgreSQL 和 MyBatis Plus 的步骤与 MyBatis 类似,只不过在 MyBatis Plus 中提供了更多的便利功能,如自动生成 SQL、分页查询、Wrapper 查询等。
970 2
|
10月前
|
Java 测试技术 Spring
简单学Spring Boot | 博客项目的测试
本内容介绍了基于Spring Boot的博客项目测试实践,重点在于通过测试驱动开发(TDD)优化服务层代码,提升代码质量和功能可靠性。案例详细展示了如何为PostService类编写测试用例、运行测试并根据反馈优化功能代码,包括两次优化过程。通过TDD流程,确保每项功能经过严格验证,增强代码可维护性与系统稳定性。
364 0
|
10月前
|
存储 Java 数据库连接
简单学Spring Boot | 博客项目的三层架构重构
本案例通过采用三层架构(数据访问层、业务逻辑层、表现层)重构项目,解决了集中式开发导致的代码臃肿问题。各层职责清晰,结合依赖注入实现解耦,提升了系统的可维护性、可测试性和可扩展性,为后续接入真实数据库奠定基础。
753 0
|
分布式计算 大数据 Java
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
268 0
|
Web App开发 消息中间件 Prometheus
Spring Boot 服务监控,健康检查,线程信息,JVM堆信息,指标收集,运行情况监控等!(一)
Spring Boot 服务监控,健康检查,线程信息,JVM堆信息,指标收集,运行情况监控等!
|
JSON 监控 安全
Spring Boot 服务监控,健康检查,线程信息,JVM堆信息,指标收集,运行情况监控等!(二)
Spring Boot 服务监控,健康检查,线程信息,JVM堆信息,指标收集,运行情况监控等!
|
Prometheus 监控 Cloud Native
SpringBoot服务监控机制,总算整明白了!
SpringBoot服务监控机制,总算整明白了!
SpringBoot服务监控机制,总算整明白了!
|
缓存 监控 Java
[原创]SpringBoot服务监控-SpringBootAdmin
[原创]SpringBoot服务监控-SpringBootAdmin
[原创]SpringBoot服务监控-SpringBootAdmin