java动态配置_JAVA 动态配置 (配置源={properties,redis})

每次修改配置还得重启,感觉很麻烦

卤主现在用的是properties,redis做配置,因为没有用到mysql等关系型数据库

贴代码

全局Application Config 代码

package com.shield.device;

import java.util.HashMap;

import java.util.Map;

import com.shield.cache.CacheKey;

import com.shield.cache.CacheService;

import com.shield.cache.springredis.RedisService;

import com.shield.springcontext.ContextUtils;

import com.shield.springcontext.CustomizedPropertyConfigurer;

import com.shield.util.JsonUtil;

public class AppConfig {

private static final AppConfig appconfig = new AppConfig() ;

private CacheService redisService ;

private final Map cache = new HashMap();

private AppConfig(){

redisService = ContextUtils.getBean(RedisService.class);

}

public static boolean getBoolean(String key) {

Object o = getObject(key);

if(o instanceof Boolean){

return (Boolean)o ;

}

return Boolean.parseBoolean(key);

}

public static String getString(String key){

Object o = getObject(key);

if(o instanceof String){

return (String)o ;

}

return o.toString();

}

public static float getFloat(String key) {

Object o = getObject(key);

if(o instanceof Float){

return (float)o ;

}

if(o instanceof String){

return Float.parseFloat((String)o) ;

}

return Float.parseFloat(o.toString());

}

public static int getInt(String key){

Object o = getObject(key);

if(o instanceof Integer){

return (int)o ;

}

if(o instanceof String){

return Integer.parseInt((String)o) ;

}

return Integer.parseInt(o.toString());

}

public static void put(String key, String value) {

appconfig.redisService.setHashValue(CacheKey.APP_CONFIG, key, value);

appconfig.cache.put(key, value);

}

public static String cacheToString() {

return JsonUtil.objectToJson(appconfig.cache);

}

public static String contextPropertyToString() {

return JsonUtil.objectToJson(CustomizedPropertyConfigurer.getContextPropertyMap());

}

public static Object getObject(String key){

Object o = appconfig.cache.get(key);

if(o == null){

o = appconfig.redisService.getHashValue(CacheKey.APP_CONFIG, key);

if(o != null){

appconfig.cache.put(key, o);

}

}

if(o == null){

o = CustomizedPropertyConfigurer.getContextProperty(key);

if(o != null){

appconfig.cache.put(key, o);

}

}

if(o == null){

throw new RuntimeException("Properties key: "+key +" value is empty, please check it.");

}

return o;

}

public static void flushAll(){

appconfig.cache.clear();

}

}

flushAll就是清除掉数据,比如redis的配置修改了。

推荐在http访问时候调用

如:

curl localhost:8080/config/reload

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值