SpringBoot整合Nacos自动刷新配置

本文涉及的产品
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
简介: Nacos作为SpringBoot服务的注册中心和配置中心。在NacosServer中修改配置文件,在SpringBoot不重启的情况下,获取到修改的内容。本例将在配置文件中配置一个 cml.age=100 的配置项,程序中编写一个方法读取配置文件,并通过 Get--->/test/age 接口提供给浏览器访问。若配置文件中的 age 修改为 200 ,不用重新启动程序,直接访问 /test/age 接口,将获取到最新的值 200若配置文件中没有age 的配置项,或干脆没有 cml 的配置项,访问 /test/age 接口将返回默认的值 18

目的

Nacos作为SpringBoot服务的注册中心和配置中心。

在NacosServer中修改配置文件,在SpringBoot不重启的情况下,获取到修改的内容。

本例将在配置文件中配置一个 cml.age=100 的配置项,程序中编写一个方法读取配置文件,并通过 Get--->/test/age 接口提供给浏览器访问。

  • 若配置文件中的 age 修改为 200 ,不用重新启动程序,直接访问 /test/age 接口,将获取到最新的值 200
  • 若配置文件中没有age 的配置项,或干脆没有 cml 的配置项,访问 /test/age 接口将返回默认的值 18

环境

  • SpringCloud:2020.0.3
  • SpringCloudAlibaba:2021.1
  • SpringBoot:2.5.2

pom

pom中引入 nacos 相关配置:discovery,config,bootstrap

网上有人说,需要引入 actuator ,其实不用。也没有 SpringSecurity 拦截的问题,NacosClient 端定时从 NacosServer 端拉取最新配置,以http方式请求。


  <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring.cloud.dependencies}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring.cloud.alibaba.dependencies}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <!-- nacos-discovery -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
           <!--nacos config -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
         <!--bootstrap-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
        </dependency>
    </dependencies>

配置文件

bootstrap.yml


server:
  port: 9556
spring:
  application:
    name: app
  profiles:
    active: test
    nacos:
      discovery:
        username: nacos
        password: nacos
        server-addr: 192.168.1.61:8848
      config:
        server-addr: 192.168.1.61:8848
        file-extension: yaml

app-dev.yaml

此配置指 NacosServer 中的配置文件 app-dev.yaml ,仅截取 cml.age 部分

cml:
   age: 100

代码

  • RefreshScope注解:必须加在 controller 上面,加在主启动内上面不好使。哪些资源需要自动刷新配置就在该controller上面添加此注解,可封装一个 BaseController 。
  • @Value("${cml.age:18}"):读取配置文件中的 cml.age 配置项值,赋给变量 age ,默认值为 18
  • getAge:获取年龄接口
  • /test/age接口需要添加到 Security.permitAll

问题:RefreshScope注解为什么一定要添加在 controller 上面?为什么在主启动类上面添加不生效


     @RefreshScope
     @Api(tags = "测试 - api")
     @Slf4j
     @RestController
     @RequestMapping("/test")
     public class TestController {

         /**
          * 获取配置文件中的 cml.age 内容,若未获取到,默认值为18
          */
         @Value("${cml.age:18}")
         private String age;

         @ApiOperation(value = "获取年龄 - 测试配置自动刷新", notes = "获取年龄 - 测试配置自动刷新")
         @GetMapping("/age")
         public String getAge() {
             return age;
         }
     }

日志

开启 nacos-refresh 日志,打印配置内容更新情况

logging:
  level:
     com.alibaba.cloud.nacos.refresh: debug

打印的日志:

2022-01-28 13:43:30.574 [com.alibaba.nacos.client.Worker.longPolling.fixed-192.168.1.61_8848-zjrkm-admin] DEBUG com.alibaba.cloud.nacos.refresh.NacosContextRefresher.innerReceive:136 - Refresh Nacos config group=DEFAULT_GROUP,dataId=identityQrCodeAdmin-service-cml-test.yaml,configInfo=spring:
  application:
    name: 
    .
    .
    .
    .
    .

测试

在不重启SpringBoot服务的情况,多次在 NacosServer 中修改 cml.age 配置项的值,然后通过浏览器访问 /test/age 接口,发现每次都可以获取到最新的 age 值。

特殊的情况

当项目集成了 SpringSecurity 的时候,如果在 UserDetailsService 实现类上添加 RefreshScope 注解,并在类中直接使用 @Value 获取配置文件的内容,会导致用户在登录的时候找不到该类,从而无法调用loadUserByUsername 方法做用户名密码校验,进而登录功能无法使用。

解决方案是:

  • 新建一个配置类(假设类名为 Account ),使用 ConfigurationProperties 将需要的配置注入到类属性;并在类上添加 RefreshScope 注解
  • 将 Account 类注入容器,UserDetailsService 实现类中将 Account 类 Autowired 进来再使用

核心代码:
Account 类:


import lombok.Data;
import lombok.ToString;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import java.io.Serializable;
@RefreshScope
@Component
@ConfigurationProperties(prefix = "cml.admin")
@Data
@ToString
public class Account  implements Serializable {
    private  String defaultUserName;
    private  String defaultPassword;
    private  String defaultUserName1;
    private  String defaultPassword1;
}

UserDetailsService 实现类:


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class UserService implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private Account account;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (account.getDefaultUserName().equals(username)) {
            String password = passwordEncoder.encode(account.getDefaultPassword());
            return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
        }
        if (account.getDefaultUserName1().equals(username)) {
            String password = passwordEncoder.encode(account.getDefaultPassword1());
            return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin1"));
        }
        return null;
    }
}
目录
相关文章
|
1天前
|
Dubbo Java 应用服务中间件
微服务学习 | Springboot整合Dubbo+Nacos实现RPC调用
微服务学习 | Springboot整合Dubbo+Nacos实现RPC调用
|
1天前
|
安全 Java 开发者
深入理解Spring Boot配置绑定及其实战应用
【4月更文挑战第10天】本文详细探讨了Spring Boot中配置绑定的核心概念,并结合实战示例,展示了如何在项目中有效地使用这些技术来管理和绑定配置属性。
13 1
|
1天前
|
SpringCloudAlibaba 应用服务中间件 Nacos
【微服务 SpringCloudAlibaba】实用篇 · Nacos配置中心(下)
【微服务 SpringCloudAlibaba】实用篇 · Nacos配置中心
10 0
|
1天前
|
Java 文件存储 Spring
【springboot】logback配置
【springboot】logback配置
20 1
|
1天前
|
Java 微服务 Spring
Spring Boot中获取配置参数的几种方法
Spring Boot中获取配置参数的几种方法
22 2
|
1天前
|
Nacos
nacos 配置页面的模糊查询
nacos 配置页面的模糊查询
|
1天前
|
Web App开发 前端开发 Java
SpringBoot配置HTTPS及开发调试
在实际开发过程中,如果后端需要启用https访问,通常项目启动后配置nginx代理再配置https,前端调用时高版本的chrome还会因为证书未信任导致调用失败,通过摸索整理一套开发调试下的https方案,特此分享
21 0
SpringBoot配置HTTPS及开发调试
|
1天前
|
存储 Java 数据库
SpringBoot使用jasypt实现数据库配置加密
这样,你就成功地使用Jasypt实现了Spring Boot中的数据库配置加密,确保敏感信息在配置文件中以加密形式存储,并在应用启动时自动解密。
47 2
|
1天前
|
机器学习/深度学习 Java Nacos
Nacos 配置中心(2023旧笔记)
Nacos 配置中心(2023旧笔记)
21 0
|
1天前
|
存储 前端开发 Java
第十一章 Spring Cloud Alibaba nacos配置中心
第十一章 Spring Cloud Alibaba nacos配置中心
27 0