java实时更新配置_spring boot 配置动态刷新实现详解

本文测试使用的spring cloud版本为:

Dalston.SR1

很多朋友只知道spring cloud config可以刷新远程git的配置到内存中,

却不知道spring cloud config的客户端可以脱离服务端使用,

更不知道spring cloud config客户端结合actuator还可以刷新本地的配置文件到内存中。

具体做法如下:

1、pom:

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">

4.0.0

com.liuyx

test-config-refresh

1.0-SNAPSHOT

org.springframework.boot

spring-boot-starter-parent

1.5.4.RELEASE

org.springframework.boot

spring-boot-starter-web

org.springframework.cloud

spring-cloud-starter-config

org.springframework.boot

spring-boot-starter-actuator

org.springframework.cloud

spring-cloud-dependencies

Dalston.SR1

pom

import

单独引入 spring-boot-starter-actuator或者spring-cloud-starter-config(spring cloud config的客户端) 是不会暴露/refresh端点的,两者同时引入之后才能暴露/refresh端点。

2、一般使用spring-cloud-starter-config的文章都会让你在bootstrap里加上配置中心服务端的地址,这里我们要脱离配置中心服务端使用,所以这些配置完全不需要。

3、对需要刷新的属性使用@Value注解,同时将类使用@RefreshScope注解进行标记,示例如下:

package com.liuyx.test;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.context.config.annotation.RefreshScope;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication

@RestController

@RefreshScope

public class Main {

public static void main(String[] args) {

SpringApplication.run(Main.class);

}

private static int port;

@Value("${server.port}")

public void setPort(int port){

this.port=port;

}

@RequestMapping("/port")

public int port(){

return port;

}

}

这里我的变量是一个static变量,所以只能在非static的set方法上加@Value注解,而不是变量定义行的上方。如果不是静态变量则可以直接写作:

@Value("${server.port}")

private int port;

4、application.properties配置

server.port=80

local.test=hello1

management.security.enabled=false

5、测试

1、启动项目,访问 http://localhost/port 显示 80

2、修改classpath(注意是classpath,即你编译后的class文件所处的目录)下的application.properties将server.port改为801

36c3c190b70a8bc3851c0da2fcf3f0af.png

3、发送空post(注意是post)请求到 http://localhost:80/refresh

0e0027000a8640c91b20ce50db6df63e.png

4、再次访问 http://localhost/port 显示 801 测试成功

最后的补充:

即使结合配置中心服务端使用,该方法也是有效的,所有有效位置的有效配置文件(如git上的,jar内的,jar外的)都会被扫描,并根据一定的顺序进行覆盖

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值