la.renzhen.rtpt.config.source.RedisConfigurationSource Maven / Gradle / Ivy
package la.renzhen.rtpt.config.source;
import la.renzhen.rtpt.config.ConfigurationSource;
import redis.clients.jedis.Jedis;
import java.util.*;
/**
*
*
* @author haiker
* @version 30/05/2018 12:06 AM
*/
public class RedisConfigurationSource implements ConfigurationSource {
String module;
Jedis jedis;
public RedisConfigurationSource(String module, Jedis jedis) {
this.module = module;
this.jedis = jedis;
}
@Override
public Map loadAll(String environment, String prefix) {
prefix = Optional.ofNullable(prefix).orElse("");
String redisPattern = String.format("%s:%s:%s*", module, environment, prefix);
int length = String.format("%s:%s:", module, environment).length();
Map values = new HashMap<>();
Set keySets = jedis.keys(redisPattern);
if (keySets.isEmpty()) {
return values;
}
String[] keys = new String[keySets.size()];
Iterator it = keySets.iterator();
for (int i = 0; i < keySets.size(); i++) {
keys[i] = it.next();
}
List valueList = jedis.mget(keys);
int i = 0;
for (String key : keys) {
String rkey = key.substring(length);
String value = valueList.get(i++);
values.put(rkey, value);
}
return values;
}
@Override
public String get(String environment, String key) {
String redisKey = String.format("%s:%s:%s", module, environment, key);
return jedis.get(redisKey);
}
}