创建方式一通过配置文件创建以及加载初始化redis配置
1.新建属性配置文件 redis.properties
2.新建配置文件 spring-redis.xml
3.在web.xml里面加载配置文件
4.在spring配置文件里面加载redis的属性配置文件
5.redis相关工具类 RedisUtils
6.其他地方使用就 RedisUtils.方法名
创建方式二通过JedisPoolConfig代码创建链接
在RedisUtils 里面获取redis的方法中增加初始化配置,当程序调用到redis相关方法才创建链接
redis.properties 配置如下
#连接IP地址
redis.host=127.0.0.1
#端口号
redis.port=6379
#密码
redis.password=123456
#使用的数据库
redis.database=4
#超时时间
redis.timeout=10000
#最大空闲数
redis.maxIdle=300
#最大空连接数
redis.maxTotal=10
#最大等待时间
redis.maxWaitMillis=30
#获取连接时,检测连接是否成功
redis.testOnBorrow=true
spring-redis.xml 配置如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd"
default-autowire="byName" default-lazy-init="false">
<!-- Jedis链接池配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 最大空闲数 -->
<property name="maxIdle" value="${redis.maxIdle}" />
<!-- 最大空连接数 -->
<property name="maxTotal" value="${redis.maxTotal}" />
<!-- 最大等待时间 -->
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<!-- 连接超时时是否阻塞,false时报异常,ture阻塞直到超时, 默认true -->
<!-- <property name="blockWhenExhausted" value="${redis.blockWhenExhausted}" /> -->
<!-- 获取连接时,检测连接是否成功 -->
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="jedisPoolConfig"/>
<constructor-arg index="1" value="${redis.host}" type="java.lang.String"/>
<constructor-arg index="2" value="${redis.port}" type="int"/> <!-- port-->
<constructor-arg index="3" value="${redis.timeout}" type="int"/>
<constructor-arg index="4" value="${redis.password}" type="java.lang.String"/>
<constructor-arg index="5" value="${redis.database}" type="int"/>
</bean>
<!-- 以下是spring-data-redis配置方式 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.host}" p:password="${redis.password}" p:port="${redis.port}" p:pool-config-ref="jedisPoolConfig"/>
<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
</bean>
<!-- 使用spring-session把http session放到redis里 -->
<!-- <bean id="redisHttpSessionConfiguration"
class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<property name="maxInactiveIntervalInSeconds" value="1800" />
</bean> -->
<!-- redis的相关工具类 -->
<bean id="RedisUtils" class="com.growatt.oss.method.redis.RedisUtils">
<property name="jedisPool" ref="jedisPool"></property>
<!-- <property name="jedisConnectionFactory" ref="connectionFactory"></property> -->
</bean>
</beans>
web.xml 里面需要新增的内容,找到加载spring的配置的位置增加redis的配置即可
spring配置文件里面加载redis的属性配置文件 二种方式根据实际情况选择,加载多个配置文件就选择方式二多个以逗号分开
<context:property-placeholder location="classpath:redis.properties" /> <!-- 方式一 只有一个配置文件-->
<context:property-placeholder location="classpath:jdbc.properties,classpath:redis.properties " /> <!-- 方式二 加载多个配置文件-->
RedisUtils
package com.growatt.oss.method.redis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.growatt.oss.method.OUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.growatt.oss.system.StaticParamsUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Pipeline;
/**
* redis缓存工具类
* ps说明,经过测试:1.存值的时候如果key和value都是经过序列化SerializeUtils.serialize(key)的处理,那么相应取值的时候也要经过反序列化处理的方法取
* 2.如果存值的时候key和value没有经过序列化的方式处理,那么取值的时候也不要用经过反序列化的处理的方法取
* 3.目前因为没有需要,所以方法的key都是没有经过序列化处理的,但是有些方法的value是经过序列化的,所以要注意用相应的取值的方法
* 如:1) set(key,SerializeUtils.serialize(value)),那么取值就是:get(key,SerializeUtils.unSerialize(value))
* 2) set(SerializeUtils.serialize(key),SerializeUtils.serialize(value))那么取值则为:get(SerializeUtils.unSerialize(key),SerializeUtils.unSerialize(value))
* 3) set(key,value)那么取值则为:get(key,value)
* 规则:存key值的时候请按业务定义一个前缀,最好设置好有效时间,且key的长度不要过长
*
*/
public class RedisUtils {
private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);
private static int POOLTYPE = 1;//连接池类型 1单节点 2集群 默认1
/**
* 非切片链接池
* 单节点
*/
public static JedisPool jedisPool;
// 方式二使用
static void init(){
String isOpenRedis = StaticParamsUtils.getConfigPropert("redis.open")+ "";
if(jedisPool == null && !"false".equals(isOpenRedis)){
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(200);//最大空闲链接
poolConfig.setMaxTotal(500);//最大连接数
poolConfig.setMaxWaitMillis(1000 * 10);//最大等待毫秒数
poolConfig.setTestOnBorrow(true);//获取链接检查有效性
poolConfig.setTestOnReturn(false);//返回验证
poolConfig.setBlockWhenExhausted(true);//链接好近是否阻塞
poolConfig.setTestOnCreate(true);//部署时 为True;
String host = StaticParamsUtils.getConfigPropert("redis.host");
int port = Integer.valueOf(StaticParamsUtils.getConfigPropert("redis.port"));
int timeout = Integer.valueOf(StaticParamsUtils.getConfigPropert("redis.timeout"));
String password = StaticParamsUtils.getConfigPropert("redis.password");
int database = Integer.valueOf(StaticParamsUtils.getConfigPropert("redis.database"));
if(!OUtils.isNull(host) && !OUtils.isNull(password)){
jedisPool = new JedisPool(poolConfig, host, port, timeout, password, database);
logger.error("RedisUtils 连接成功:host= "+ host +" : database= " + database);
}
}
}
/**
* 获取一个jedis 客户端
* getJedis().select(1); 选择第几个DB
*
* @return
*/
private synchronized static Jedis getJedis() {
Jedis jedis = null;
// RedisUtils.init(); // 方式二使用 方式一的话 需要注释掉该方法的调用
if (POOLTYPE == 1 && jedisPool != null) {
try {
jedis = jedisPool.getResource();
} catch (Exception e) {
logger.error("Redis getJedis 失败 :" + e);
return null;
}
//jedisConnectionFactory.getShardInfo().createResource();//.getConnection().getNativeConnection();
} else {
// jedis = jedisSentinelPool.getResource();
}
return jedis;
}
/**
* 释放redis资源
*
* @param jedis
*/
private static void releaseResource(Jedis jedis) {
if (jedis != null) {
if (POOLTYPE == 1) {
try {
jedis.close();
} catch (Exception e) {
logger.error("Redis releaseResource(Jedis jedis)失败 :" + e);
}
} else {
// 待定
}
}
}
/**
* 删除Redis中的所有key
*
* @throws Exception
*/
public synchronized static void flushAll() {
Jedis jedis = getJedis();
if(jedis != null){
try {
jedis.flushAll();
} catch (Exception e) {
logger.error("Redis flushAll失败 :" + e);
} finally {
releaseResource(jedis);
}
}
}
/**
* 清空redis 所有数据
* 选择运行的DB环境
*
* @return
*/
public synchronized static String flushDB(int DBIndex) {
Jedis jedis = getJedis();
if(jedis == null){
return null;
}
try {
jedis.select(DBIndex);
return jedis.flushDB();
} catch (Exception e) {
logger.error("Redis flushDB(int DBIndex)失败 :" + e);
return null;
} finally {
releaseResource(jedis);
}
}
/**
* 清空redis 所有数据
* 当前运行的DB环境
*
* @return
*/
public synchronized static String flushDB() {
Jedis jedis = getJedis();
if(jedis == null){
return null;
}
try {
return jedis.flushDB();
} catch (Exception e) {
logger.error("Redis flushDB失败 :" + e);
return null;
} finally {
releaseResource(jedis);
}
}
/**
* 保存一个对象到Redis中(缓存过期时间:使用此工具类中的默认时间) . <br/>
*
* @param key 键 . <br/>
* @param object 缓存对象 . <br/>
* @return true or false . <br/>
* @throws Exception
*/
public synchronized static Boolean save(String key, Object object) {
return save(key, object, 0);
}
/**
* 保存一个对象到redis中并指定过期时间
*
* @param key 键 . <br/>
* @param object 缓存对象 . <br/>
* @param seconds 过期时间(单位为秒).<br/>
* @return true or false .
*/
public synchronized static Boolean save(String key, Object object, int seconds) {
Jedis jedis = getJedis();
if(jedis == null){
return false;
}
try {
jedis.del(key);
jedis.set(key.getBytes(), SerializeUtils.serialize(object));
if (seconds != 0) {
jedis.expire(key.getBytes(), seconds);
}
return true;
} catch (Exception e) {
logger.error("Redis save(String key, Object object, int seconds)失败 " + key + " :" + e);
return false;
} finally {
releaseResource(jedis);
}
}
/**
* 根据缓存键获取Redis缓存中的值.<br/>
*
* @param key 键.<br/>
* @return Object .<br/>
* @throws Exception
*/
public static Object get(String key) {
Jedis jedis = getJedis();
if(jedis == null){
return null;
}
try {
byte[] obj = jedis.get(key.getBytes());
return obj == null ? null : SerializeUtils.unSerialize(obj);
} catch (Exception e) {
logger.error("Redis get(String key)失败 " + key + " :" + e);
} finally {
releaseResource(jedis);
}
return null;
}
/**
* 根据缓存键清除Redis缓存中的值.<br/>
*
* @param key
* @return
* @throws Exception
*/
public static Boolean del(String key) {
Jedis jedis = getJedis();
if(jedis == null){
return false;
}
try {
jedis.del(key);
return true;
} catch (Exception e) {
logger.error("Redis del(String key)失败 "+ key +" :"+ e);
return false;
} finally {
releaseResource(jedis);
}
}
/**
* 根据缓存键清除Redis缓存中的值.<br/>
*
* @param keys
* @return
* @throws Exception
*/
public static Boolean del(String... keys) {
Jedis jedis = getJedis();
if(jedis == null){
return false;
}
try {
jedis.del(keys);
return true;
} catch (Exception e) {
logger.error("Redis del(String... keys)失败 "+ keys +" :" + e);
return false;
} finally {
releaseResource(jedis);
}
}
/**
* 设置指定key的超时时间
*
* @param key
* @param seconds 超时时间(单位为秒)
* @return
*/
public static Boolean expire(String key, int seconds) {
Jedis jedis = getJedis();
if(jedis == null){
return false;
}
try {
if (seconds != 0) {
jedis.expire(key, seconds);
}
return true;
} catch (Exception e) {
logger.error("Redis expire(String key, int seconds)失败 "+ key +" :"+ e);
return false;
} finally {
releaseResource(jedis);
}
}
/**
* 去掉key的有效时间
*
* @param key
* @return
*/
public static Boolean persist(String key) {
Jedis jedis = getJedis();
if(jedis == null){
return false;
}
try {
jedis.persist(key);
return true;
} catch (Exception e) {
logger.error("Redis persist(String key)失败 " + key + " :" + e);
return false;
} finally {
releaseResource(jedis);
}
}
/**
* 添加一个内容到指定key的hash中
*
* @param key
* @param field
* @param value
* @return
*/
public static Boolean addHash(String key, Object field, Object value) {
Jedis jedis = getJedis();
if(jedis == null){
return false;
}
try {
jedis.hset(key.getBytes(), SerializeUtils.serialize(field), SerializeUtils.serialize(value));
return true;
} catch (Exception e) {
logger.error("Redis addHash(String key, Object field, Object value)失败 "+ key +" :field ["+ field +"]" + e);
return false;
} finally {
releaseResource(jedis);
}
}
/**
* 从指定hash中拿一个对象
*
* @param key
* @param field
* @return
*/
public static Object getHash(String key, Object field) {
Jedis jedis = getJedis();
if(jedis == null){
return null;
}
try {
byte[] obj = jedis.hget(key.getBytes(), SerializeUtils.serialize(field));
return SerializeUtils.unSerialize(obj);
} catch (Exception e) {
logger.error("Redis getHash(String key, Object field)失败 "+ key +" :field ["+ field +"]"+ e);
return null;
} finally {
releaseResource(jedis);
}
}
/**
* 从hash中删除指定filed的值
*
* @param key
* @param field
* @return
*/
public static Boolean delHash(String key, Object field) {
Jedis jedis = getJedis();
if(jedis == null){
return false;
}
try {
long result = jedis.hdel(key.getBytes(), SerializeUtils.serialize(field));
return result == 1 ? true : false;
} catch (Exception e) {
logger.error("Redis delHash(String key, Object field)失败 "+ key +" :field ["+ field +"]"+ e);
return null;
} finally {
releaseResource(jedis);
}
}
/**
* 获得hash中的所有key value
*
* @param key
* @return
*/
public static Map<byte[], byte[]> getAllHash(String key) {
Jedis jedis = getJedis();
if(jedis == null){
return null;
}
try {
Map<byte[], byte[]> map = jedis.hgetAll(key.getBytes());
return map;
} catch (Exception e) {
logger.error("Redis getAllHash(String key)失败 " + key + " :" + e);
return null;
} finally {
releaseResource(jedis);
}
}
/**
* 通过key删除(字节)
*
* @param key
*/
public static void del(byte[] key) {
Jedis jedis = getJedis();
if(jedis != null){
try {
jedis.del(key);
} catch (Exception e) {
logger.error("Redis del(byte[] key)失败 "+ key +" :" + e);
} finally {
releaseResource(jedis);
}
}
}
/**
* 添加key value 并且设置存活时间(字节)
*
* @param key
* @param value
* @param liveTime
*/
public static void set(byte[] key, byte[] value, int liveTime) {
Jedis jedis = getJedis();
if(jedis != null){
try {
set(key, value);
if (liveTime != 0) {
jedis.expire(key, liveTime);
}
} catch (Exception e) {
logger.error("Redis set(byte[] key, byte[] value, int liveTime)失败 "+ key +" :" + e);
} finally {
releaseResource(jedis);
}
}
}
/**
* 添加key value 并且设置存活时间(String)
*
* @param key
* @param value
* @param expire,单位毫秒
*/
public static void setString(String key, String value, int expire) {
Jedis jedis = getJedis();
if(jedis != null){
try {
setString(key, value);
if (expire != 0) {
jedis.expire(key, expire);
}
} catch (Exception e) {
logger.error("Redis setString(String key, String value, int expire)失败 "+ key +" :" + e);
} finally {
releaseResource(jedis);
}
}
}
public static String getString(String key) {
Jedis jedis = getJedis();
if(jedis == null){
return null;
}
try {
return jedis.get(key);
} catch (Exception e) {
logger.error("Redis getString(String key)失败 "+ key +" :" + e);
} finally {
releaseResource(jedis);
}
return null;
}
public static Object getObject(String key) {
Jedis jedis = getJedis();
if(jedis == null){
return null;
}
try {
return SerializeUtils.unSerialize(jedis.get(key.getBytes()));
} catch (Exception e) {
logger.error("Redis getObject(String key)失败 "+ key +" :" +e);
} finally {
releaseResource(jedis);
}
return null;
}
/**
* 存放对象
*
* @param key
* @param value
*/
public static void setObject(String key, Object value) {
Jedis jedis = getJedis();
if(jedis != null){
try {
jedis.set(key.getBytes(), SerializeUtils.serialize(value));
} catch (Exception e) {
logger.error("Redis setObject(String key, Object value)失败 "+ key +" :" + e);
} finally {
releaseResource(jedis);
}
}
}
/**
* 存放对象
*
* @param key
* @param value
* @param expire,单位毫秒
*/
public static void setObject(String key, Object value, int expire) {
Jedis jedis = getJedis();
if(jedis != null){
try {
setObject(key, value);
if (expire != 0) {
jedis.expire(key, expire);
}
} catch (Exception e) {
logger.error("Redis setObject(String key, Object value, int expire)失败 "+ key +" :" + e);
} finally {
releaseResource(jedis);
}
}
}
/**
* 添加key value(String)
*
* @param key
* @param value
*/
public static void setString(String key, String value) {
Jedis jedis = getJedis();
if(jedis != null){
try {
//jedis.del(key);
jedis.set(key, value);
} catch (Exception e) {
logger.error("Redis setString(String key, String value)失败 " + key + " :"+ e);
} finally {
releaseResource(jedis);
}
}
}
/**
* 添加key value (字节)(序列化)
*
* @param key
* @param object
*/
public static void set(String key, Object object) {
Jedis jedis = getJedis();
if(jedis != null){
try {
jedis.set(key.getBytes(), SerializeUtils.serialize(object));
} catch (Exception e) {
logger.error("Redis set(String key, Object object)失败 "+ key +" :" + e);
} finally {
releaseResource(jedis);
}
}
}
/**
* 添加key value (字节)(序列化)
*
* @param key
* @param object
*/
public static void set(String key, Object object, int expire) {
Jedis jedis = getJedis();
if(jedis != null){
try {
jedis.set(key.getBytes(), SerializeUtils.serialize(object));
if (expire != 0) {
jedis.expire(key.getBytes(), expire);
}
} catch (Exception e) {
logger.error("Redis set(String key, Object object, int expire)失败 "+ key +" :" + e);
} finally {
releaseResource(jedis);
}
}
}
/**
* 添加key value (字节)(序列化)
*
* @param key
* @param value
*/
public static void set(byte[] key, byte[] value) {
Jedis jedis = getJedis();
if(jedis != null){
try {
jedis.set(key, value);
} catch (Exception e) {
logger.error("Redis set(byte[] key, byte[] value)失败 "+ key +" :" + e);
} finally {
releaseResource(jedis);
}
}
}
/**
* 获取redis value (String)
*
* @param key
* @return
*/
public static String getReturnString(String key) {
Jedis jedis = getJedis();
if(jedis == null){
return null;
}
try {
String value = jedis.get(key);
return value;
} catch (Exception e) {
logger.error("Redis getReturnString(String key)失败 "+ key +" :" + e);
return null;
} finally {
releaseResource(jedis);
}
}
/**
* 获取redis value (byte [] )(反序列化)
*
* @param key
* @return
*/
public static byte[] get(byte[] key) {
Jedis jedis = getJedis();
if(jedis == null){
return null;
}
try {
return jedis.get(key);
} catch (Exception e) {
logger.error("Redis get(byte[] key)失败 "+ key +" :" + e);
return null;
} finally {
releaseResource(jedis);
}
}
/**
* 设置List集合
*
* @param key
* @param list
*/
public static void setList(String key, List<?> list) {
Jedis jedis = getJedis();
if(jedis != null){
try {
jedis.del(key);
if (null != list) {
jedis.set(key.getBytes(), SerializeUtils.serializeList(list));
} else {//如果list为空,则设置一个空
jedis.set(key.getBytes(), "".getBytes());
}
} catch (Exception e) {
logger.error("Redis setList(String key, List<?> list)失败 "+ key +" :" + e);
} finally {
releaseResource(jedis);
}
}
}
/**
* 设置List集合 以及缓存时效
*
* @param key
* @param list
*/
public static void setList(String key, List<?> list, int liveTime) {
Jedis jedis = getJedis();
if(jedis != null){
try {
if (null != list) {
jedis.set(key.getBytes(), SerializeUtils.serializeList(list));
if (liveTime != 0) {
jedis.expire(key.getBytes(), liveTime);
}
} else {//如果list为空,则设置一个空
jedis.set(key.getBytes(), "".getBytes());
}
} catch (Exception e) {
logger.error("Redis setList(String key, List<?> list, int liveTime)失败 "+ key +" :" + e);
} finally {
releaseResource(jedis);
}
}
}
/**
* 获取List集合
*
* @param key
* @return
*/
public static List<?> getList(String key) {
Jedis jedis = getJedis();
try {
if (jedis == null || !jedis.exists(key)) {
return null;
}
byte[] data = jedis.get(key.getBytes());
return SerializeUtils.unserializeList(data);
} catch (Exception e) {
logger.error("Redis getList(String key)失败 "+ key +" :" + e);
return null;
} finally {
releaseResource(jedis);
}
}
/**
* 把某个值放入List
* List<string>
*
* @param key
* @param data
*/
public static void pushDataToList(String key, String data, int liveTime, String methodName) {
Jedis jedis = getJedis();
if(jedis != null){
try {
jedis.rpush(key, data);
if (liveTime != 0) {
jedis.expire(key, liveTime);
}
} catch (Exception e) {
logger.error("Redis pushDataToList(String key, String data, int liveTime, String methodName)失败 "+ key +" :" + e);
} finally {
releaseResource(jedis);
}
}
}
/**
* 删除list中的元素
*
* @param key
* @param values
*/
protected void deleteDataFromList(String key, List<String> values) {
Jedis jedis = getJedis();
if(jedis != null){
try {
Pipeline pipeline = jedis.pipelined();
if (values != null && !values.isEmpty()) {
for (String val : values) {
pipeline.lrem(key, 0, val);
}
}
pipeline.sync();
} catch (Exception e) {
logger.error("Redis deleteDataFromList(String key, List<String> values)失败 "+ key +" :" + e);
} finally {
releaseResource(jedis);
}
}
}
/**
* 从List<String>转化为List<Map<String, String>>
*
* @param results
* @param cols
* @return
* @date 2014-11-27
*/
public List<Map<String, String>> getListMapByResultListString(List<String> results, String... cols) {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
int i = 1;
int x = 0;
for (String str : results) {
Map<String, String> map;
if (i == 1) {
map = new HashMap<String, String>();
list.add(map);
} else {
map = list.get(x);
}
map.put(cols[i - 1], str);
if (i == cols.length) {
i = 1;
x++;
} else {
i++;
}
}
return list;
}
/**
* 拿到缓存中所有符合pattern的key
*
* @param pattern *表示所有 或者如表达式:dict.*
* @return
*/
public static Set<String> keys(String pattern) {
Jedis jedis = getJedis();
if(jedis == null){
return new HashSet<String>();
}
try {
Set<String> allKey = jedis.keys(pattern);
return allKey;
} catch (Exception e) {
logger.error("Redis keys(String pattern)失败 "+ pattern +" :" + e);
return new HashSet<String>();
} finally {
releaseResource(jedis);
}
}
/**
* 判断一个key是否存在
*
* @param key
* @return
*/
public static Boolean exists(String key) {
Jedis jedis = getJedis();
if(jedis == null){
return false;
}
Boolean result = false;
try {
result = jedis.exists(key);
return result;
} catch (Exception e) {
logger.error("Redis exists(String key)失败 "+ key +" :" + e);
return false;
} finally {
releaseResource(jedis);
}
}
/**
* 检查是否连接成功
*
* @return
*/
public static String ping() {
return getJedis().ping();
}
/**
* 查看redis里有多少数据
*/
public static long dbSize() {
return getJedis().dbSize();
}
public JedisPool getJedisPool() {
return jedisPool;
}
public void setJedisPool(JedisPool jedisPool) {
RedisUtils.jedisPool = jedisPool;
}
/**
* 保存一个对象到redis中并指定过期时间
*
* @param key 键 . <br/>
* @param object 缓存对象 . <br/>
* @param seconds 过期时间(单位为秒).<br/>
* @return true or false .
*/
public static Boolean save(String key, Object object, int seconds, int DBIndex) {
Jedis jedis = getJedis();
if(jedis == null){
return false;
}
try {
jedis.select(DBIndex);
jedis.del(key);
jedis.set(key.getBytes(), SerializeUtils.serialize(object));
if (seconds != 0) {
jedis.expire(key.getBytes(), seconds);
}
return true;
} catch (Exception e) {
logger.error("Redis save(String key, Object object, int seconds, int DBIndex)失败 "+ key +" :" + e);
return false;
} finally {
releaseResource(jedis);
}
}
/**
* 根据缓存键清除Redis缓存中的值.<br/>
*
* @param key
* @return
* @throws Exception
*/
public static Boolean del(String key, int DBIndex) {
Jedis jedis = getJedis();
if(jedis == null){
return false;
}
try {
jedis.select(DBIndex);
jedis.del(key);
return true;
} catch (Exception e) {
logger.error("Redis del(String key, int DBIndex)失败 "+ key +" :" + e);
return false;
} finally {
releaseResource(jedis);
}
}
/**
* 根据缓存键获取Redis缓存中的值.<br/>
*
* @param key 键.<br/>
* @return Object .<br/>
* @throws Exception
*/
public static Object get(String key, int DBIndex) {
Jedis jedis = getJedis();
if(jedis == null){
return null;
}
jedis.select(DBIndex);
try {
byte[] obj = jedis.get(key.getBytes());
return obj == null ? null : SerializeUtils.unSerialize(obj);
} catch (Exception e) {
logger.error("Redis get(String key, int DBIndex)失败 "+ key +" :" + e);
return null;
} finally {
releaseResource(jedis);
}
}
@SuppressWarnings("finally")
public static String getSet(String key, String value) {
Jedis jedis = null;
String result = null;
try {
jedis = getJedis();
if(jedis == null){
return null;
}
result = jedis.getSet(key, value);
} catch (Exception e) {
logger.error("Redis getSet(String key, String value)失败 "+ key +" :" + e);
} finally {
if (jedis != null) {
jedis.close();
}
return result;
}
}
@SuppressWarnings("finally")
public static Long setnx(String key, String value) {
Jedis jedis = null;
Long result = null;
try {
jedis = getJedis();
if(jedis == null){
return null;
}
result = jedis.setnx(key, value);
} catch (Exception e) {
logger.error("Redis setnx(String key, String value)失败 "+ key +" :" + e);
} finally {
if (jedis != null) {
jedis.close();
}
return result;
}
}
/**
* hash结构-插入一条值
* @param key - hash空间key
* @param field - 字段key
* @param value - 存放对象
*/
public static void hset(String key, String field, Object value) {
Jedis jedis = getJedis();
if(jedis != null){
try {
jedis.hset(key.getBytes(), field.getBytes(), SerializeUtils.serialize(value));
} catch (Exception e) {
logger.error("Redis hset(String key, String field, Object value)失败 "+ key +" :field ["+ field +"]" + e);
} finally {
releaseResource(jedis);
}
}
}
/**
*
* hash结构-插入一条值
* @param key - hash空间key
* @param field - 字段key
* @param value - 存放对象
* @param expire - 失效时间
*/
public static void hset(String key, String field, Object value, int expire) {
Jedis jedis = getJedis();
if(jedis != null){
try {
jedis.hset(key.getBytes(), field.getBytes(), SerializeUtils.serialize(value));
if (expire != 0) {
jedis.expire(key.getBytes(), expire);
}
} catch (Exception e) {
logger.error("Redis hset(String key, String field, Object value, int expire)失败 "+ key +" :field ["+ field +"]" + e);
} finally {
releaseResource(jedis);
}
}
}
/**
* 删除根据 可以 field删除hash
* @param key
* @param field
* @return
*/
public static Boolean hdel(String key, String field) {
Jedis jedis = getJedis();
if(jedis == null){
return false;
}
try {
long result = jedis.hdel(key.getBytes(), field.getBytes());
return result == 1 ? true : false;
} catch (Exception e) {
logger.error("Redis hdel(String key, String field)失败 "+ key +" :field ["+ field +"]" + e);
return null;
} finally {
releaseResource(jedis);
}
}
/**
* 从hash结构中取值
* @param key - hash空间key
* @param field- 字段key
* @return Object
*/
public static Object hget(String key, String field) {
Jedis jedis = getJedis();
if(jedis == null){
return null;
}
try {
return SerializeUtils.unSerialize(jedis.hget(key.getBytes(), field.getBytes()));
} catch (Exception e) {
logger.error("Redis hget(String key, String field)失败 "+ key +" :field ["+ field +"]" + e);
} finally {
releaseResource(jedis);
}
return null;
}
/**
* 返回当前 key值的剩余过期时间单位秒
* -1标识这个key没有失效时间,-2标识没有这个key
* @param key
* @return
*/
public static long getExpireTime(String key) {
Jedis jedis = getJedis();
if (jedis == null) {
return -9;
}
try {
return jedis.ttl(key);
} catch (Exception e) {
logger.error("Redis getExpireTime(String key, String field)失败 "+ key + e);
} finally {
releaseResource(jedis);
}
return -9;
}
}
StaticParamsUtils
package com.growatt.oss.system;
import com.growatt.basic.jdbc.ConnectionPool;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 静态变量类
*
*
*/
public class StaticParamsUtils {
/** 初始化配置文件
*/
static {
loadSystemParamsPropertiesAndODM();
}
public static Map<String,String> configPropert = new HashMap<String,String>();
/**
* SystemParam.propertites读取,以及客制化配置读取
*/
public static void loadSystemParamsPropertiesAndODM(){
String kzhFileName = "redis.properties";
Map<String,String> configInfo = readProperties(kzhFileName);
configPropert.putAll(configInfo);
}
public static Map<String,String> readProperties(String fileName){
Map<String,String> result = new HashMap<String,String>();
InputStream inputStream = null;
try {
// 加载配置文件
inputStream = new ConnectionPool().getClass().getClassLoader().getResourceAsStream(fileName);
Properties props = new Properties();
props.load(inputStream);
for(Object key : props.keySet()){
result.put((String)key, props.getProperty((String)key));
}
} catch (Exception e) {
} finally {
try {
inputStream.close();
} catch (IOException e) {
}
}
return result;
}
public static String getConfigPropert(String key){
return configPropert.get(key);
}
}