我们经常会把一些属性值以key=value的形式放在properties文件中,有的时候,我们可能会将一些经常变动的属性值放在外部系统中,比如redis或者数据库中,如果在某个时刻修改了redis中的值,如何让使用了该值的系统及时刷新系统内存中的值呢?下面我将介绍,如何在Spring环境中动态刷新属性值。
1、假设我在redis服务器上set了一个key为env,value为dev的值
2、自定义MapPropertySource并继承Spring的MapPropertySource类,在自定义的刷新类中添加refresh方法,用于定时刷新内部属性值
package com.example.spring.refresh.config;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.core.env.MapPropertySource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Map;
/**
* ClassName: RefreshPropertySource <br/>
* Description: 将外部属性,在实例化时动态注入到Spring容器中 <br/>
* Date: 2017/10/12 13:56 <br/>
*
* @author sxp(1378127237@qq.com) <br/>
* @version 1.0 <br/>
*/
@Component
@AutoConfigureAfter(RedisTemplate.class)
public class RefreshPropertySource extends MapPropertySource {
@Autowired
private StringRedisTemplate redisTemplate;
public RefreshPropertySource(String name, Map<String, Object> source) {
super(name, source);
}
public RefreshPropertySource() {
super("RefreshPropertySource", Maps.newHashMap());
}
@PostConstruct
public void setup() {
redisTemplate.opsForValue().set("env", "dev");
}
public void refresh() {
String env = redisTemplate.opsForValue().get("env");
this.source.put("env", env);
}
}
3、使用Spring的定时器机制,定时检测外部系统中属性值的变化
package com.example.spring.refresh.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
/**
* ClassName: RefreshScheduler <br/>
* Description: RefreshScheduler <br/>
* Date: 2017/10/11 10:22 <br/>
*
* @author sxp(1378127237@qq.com) <br/>
* @version 1.0 <br/>
*/
@Component
public class RefreshScheduler {
@Autowired
private ConfigurableEnvironment environment;
@Autowired
private RefreshPropertySource refreshPropertySource;
@PostConstruct
public void setup() {
environment.getPropertySources().addLast(refreshPropertySource);
}
@Scheduled(cron = "*/5 * * * * ?")
public void scheduling() {
/* 将自定的RefreshPropertySource添加到Spring的环境中定时刷新 */
environment.getPropertySources().addLast(refreshPropertySource);
System.out.println(environment.getProperty("env"));
}
}