获取redis客户端:
public class RedisClientManage {
//配置文件 这里面有redis配置
private final static String resource = "redisconnection.xml";
/**
* 获取默认Redis客户端
*
* @return 默认Redis客户端
*/
public static RedisClient getRedisClient() {
return getRedisClient("share");
}
/**
* 根据名称获取Redis客户端
*
* @param clientName 客户端名称
* @return Redis客户端
*/
public static RedisClient getRedisClient(String clientName) {
String server;
Integer port;
Integer dbIndex;
String password;
try (InputStream inputStream = new ClassLoaderWrapper().getResourceStream(resource)) {
SAXReader reader = new SAXReader();
reader.setValidation(false);
reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
Document doc = reader.read(inputStream);
Element environments = (Element) doc.selectSingleNode("/configuration/environments");
List list = environments.selectNodes("environment[@id='" + clientName + "']");
if (list.size() != 1) {
DataSourceException e = new DataSourceException(resource + "中未找到配置项:" + clientName);
LOGGER.error("读取配置异常", e);
throw e;
}
Element element = (Element) list.get(0);
Element propertyElement = (Element) element.selectSingleNode(".//property[@name=\'server\']");
server = propertyElement == null ? "127.0.0.1" : propertyElement.attributeValue("value");
propertyElement = (Element) element.selectSingleNode(".//property[@name=\'port\']");
port = propertyElement == null ? 6379 : Integer.valueOf(propertyElement.attributeValue("value"));
propertyElement = (Element) element.selectSingleNode(".//property[@name=\'dbIndex\']");
dbIndex = propertyElement == null ? 0 : Integer.valueOf(propertyElement.attributeValue("value"));
propertyElement = (Element) element.selectSingleNode(".//property[@name=\'password\']");
password = propertyElement == null ? null : propertyElement.attributeValue("value");
} catch (DocumentException e) {
LOGGER.error("读取" + resource + "抛出DocumentException", e);
throw new DataSourceException(resource + "异常");
} catch (SAXException e) {
LOGGER.error("读取" + resource + "抛出SAXException", e);
throw new DataSourceException(resource + "异常");
} catch (IOException e) {
LOGGER.error(resource + "文件流异常", e);
throw new DataSourceException(resource + "异常");
}
RedisClient redisClient = new RedisClient(server, port, dbIndex);
if (password != null) {
redisClient.setPassword(password);
}
return redisClient;
}
}
redisconnection.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<environments>
<environment id="share">
<dataSource>
<property name="server" value="192.168.1.42"/>
<property name="port" value="6380"/>
<property name="dbIndex" value="0"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
</configuration>
调用获取redis客户端代码:
private static IObjectCache getRedis(String key) {
RedisClient redisClient = RedisClientManage.getRedisClient(key);
RedisCache redis = new RedisCache();
redis.setRedisClient(redisClient);
return redis;
}
注:部分类为自己封装,只做参考!此博客为自己留存,需要者可以自己取己所需。