您的位置:首页 > 数据库 > Redis

使用spring-data-redis进行对redis的操作,封装的一些操作方法

2016-08-12 12:04 661 查看
   这个算是工作笔记吧,因为是我的实际工作内容

   spring-data-redis api地址  http://docs.spring.io/spring-data/redis/docs/current/api/

   

  依赖maven包(当前spring-data-redis的最新版本是1.7.2.RELEASE, jedis的最新版本是2.9.0):

spring-data-redis的maven仓库地址是: https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis

jedis的maven仓库地址是: https://mvnrepository.com/artifact/redis.clients/jedis

<!-- spring-data -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.4.RELEASE</version>
</dependency>

<!-- redis客户端 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.5.2</version>
</dependency>


spring-data-redis的配置文件:

<?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:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> 
<util:properties id="redisProps" location="classpath:redis.properties"/>

<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" id="stringRedisSerializer"/>

<bean class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer" id="jacksonJsonRedisSerializer">
<constructor-arg type="java.lang.Class" value="java.lang.Object"/>
</bean>

<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"
id="jdkSerializationRedisSerializer"/>

<!--     <bean class="org.codehaus.jackson.map.ObjectMapper" id="jackObjMapper"/> -->

<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="#{redisProps['redis.pool.maxActive']}"/>
<property name="maxIdle" value="#{redisProps['redis.pool.maxIdle']}"/>
<property name="maxWaitMillis" value="#{redisProps['redis.pool.maxWait']}"/>
<property name="testOnBorrow" value="#{redisProps['redis.pool.testOnBorrow']}"/>
</bean>

<bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:hostName="#{redisProps['redis.ip']}"
p:port="#{redisProps['redis.port']}"
p:timeout="#{redisProps['redis.timeout']}"
p:password="#{redisProps['redis.password']}"
p:database="#{redisProps['redis.database']}"
p:poolConfig-ref="jedisPoolConfig"
p:usePool="true"/>

<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
p:connectionFactory-ref="redisConnectionFactory"
p:keySerializer-ref="stringRedisSerializer"
p:valueSerializer-ref="jacksonJsonRedisSerializer"
p:hashKeySerializer-ref="stringRedisSerializer"
p:hashValueSerializer-ref="jacksonJsonRedisSerializer"/>

<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg ref="jedisPoolConfig"/>
<constructor-arg value="#{redisProps['redis.ip']}"/>
<constructor-arg type="int" value="#{redisProps['redis.port']}"/>
<constructor-arg type="int" value="#{redisProps['redis.timeout']}"/>
<constructor-arg type="java.lang.String" value="#{redisProps['redis.password']}"/>
<constructor-arg type="int" value="#{redisProps['redis.database']}"/>
</bean>

</beans>


redis.properties的文件内容如下,maven管理的话,可以分别设置开发环境,测试环境,预发布环境,生产环境等

redis.pool.maxActive=1024
redis.pool.maxIdle=200
redis.pool.maxWait=1000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true

#database
redis.ip=192.168.0.246
redis.port=6378
redis.password=
redis.timeout=5000
redis.database=1


工具类如下:

package com.yjy.dg.app.report.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
* ParentDao  操作字符串redis缓存方法
*            list中的操作全是按照right方式
*
* @author littlehow
* @time 2016-08-12 09:02
*/
public class RedisParentDao {
/**
* 日志记录
*/
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
protected RedisTemplate<String, String> redisTemplate;
/**
* 前缀
*/
public static final String KEY_PREFIX_VALUE = "dg:report:value:";
public static final String KEY_PREFIX_SET = "dg:report:set:";
public static final String KEY_PREFIX_LIST = "dg:report:list:";

/**
* 缓存value操作
* @param k
* @param v
* @param time
* @return
*/
protected boolean cacheValue(String k, String v, long time) {
String key = KEY_PREFIX_VALUE + k;
try {
ValueOperations<String, String> valueOps =  redisTemplate.opsForValue();
valueOps.set(key, v);
if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
return true;
} catch (Throwable t) {
logger.error("缓存[" + key + "]失败, value[" + v + "]", t);
}
return false;
}

/**
* 缓存value操作
* @param k
* @param v
* @return
*/
protected boolean cacheValue(String k, String v) {
return cacheValue(k, v, -1);
}

/**
* 判断缓存是否存在
* @param k
* @return
*/
protected boolean containsValueKey(String k) {
return containsKey(KEY_PREFIX_VALUE + k);
}

/**
* 判断缓存是否存在
* @param k
* @return
*/
protected boolean containsSetKey(String k) {
return containsKey(KEY_PREFIX_SET + k);
}

/**
* 判断缓存是否存在
* @param k
* @return
*/
protected boolean containsListKey(String k) {
return containsKey(KEY_PREFIX_LIST + k);
}

protected boolean containsKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Throwable t) {
logger.error("判断缓存存在失败key[" + key + ", error[" + t + "]");
}
return false;
}

/**
* 获取缓存
* @param k
* @return
*/
protected String getValue(String k) {
try {
ValueOperations<String, String> valueOps =  redisTemplate.opsForValue();
return valueOps.get(KEY_PREFIX_VALUE + k);
} catch (Throwable t) {
logger.error("获取缓存失败key[" + KEY_PREFIX_VALUE + k + ", error[" + t + "]");
}
return null;
}

/**
* 移除缓存
* @param k
* @return
*/
protected boolean removeValue(String k) {
return remove(KEY_PREFIX_VALUE + k);
}

protected boolean removeSet(String k) {
return remove(KEY_PREFIX_SET + k);
}

protected boolean removeList(String k) {
return remove(KEY_PREFIX_LIST + k);
}

/**
* 移除缓存
* @param key
* @return
*/
protected boolean remove(String key) {
try {
redisTemplate.delete(key);
return true;
} catch (Throwable t) {
logger.error("获取缓存失败key[" + key + ", error[" + t + "]");
}
return false;
}
/**
* 缓存set操作
* @param k
* @param v
* @param time
* @return
*/
protected boolean cacheSet(String k, String v, long time) {
String key = KEY_PREFIX_SET + k;
try {
SetOperations<String, String> valueOps =  redisTemplate.opsForSet();
valueOps.add(key, v);
if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
return true;
} catch (Throwable t) {
logger.error("缓存[" + key + "]失败, value[" + v + "]", t);
}
return false;
}

/**
* 缓存set
* @param k
* @param v
* @return
*/
protected boolean cacheSet(String k, String v) {
return cacheSet(k, v, -1);
}

/**
* 缓存set
* @param k
* @param v
* @param time
* @return
*/
protected boolean cacheSet(String k, Set<String> v, long time) {
String key = KEY_PREFIX_SET + k;
try {
SetOperations<String, String> setOps =  redisTemplate.opsForSet();
setOps.add(key, v.toArray(new String[v.size()]));
if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
return true;
} catch (Throwable t) {
logger.error("缓存[" + key + "]失败, value[" + v + "]", t);
}
return false;
}

/**
* 缓存set
* @param k
* @param v
* @return
*/
protected boolean cacheSet(String k, Set<String> v) {
return cacheSet(k, v, -1);
}

/**
* 获取缓存set数据
* @param k
* @return
*/
protected Set<String> getSet(String k) {
try {
SetOperations<String, String> setOps = redisTemplate.opsForSet();
return setOps.members(KEY_PREFIX_SET + k);
} catch (Throwable t) {
logger.error("获取set缓存失败key[" + KEY_PREFIX_SET + k + ", error[" + t + "]");
}
return null;
}

/**
* list缓存
* @param k
* @param v
* @param time
* @return
*/
protected boolean cacheList(String k, String v, long time) {
String key = KEY_PREFIX_LIST + k;
try {
ListOperations<String, String> listOps =  redisTemplate.opsForList();
listOps.rightPush(key, v);
if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
return true;
} catch (Throwable t) {
logger.error("缓存[" + key + "]失败, value[" + v + "]", t);
}
return false;
}

/**
* 缓存list
* @param k
* @param v
* @return
*/
protected boolean cacheList(String k, String v) {
return cacheList(k, v, -1);
}

/**
* 缓存list
* @param k
* @param v
* @param time
* @return
*/
protected boolean cacheList(String k, List<String> v, long time) {
String key = KEY_PREFIX_LIST + k;
try {
ListOperations<String, String> listOps =  redisTemplate.opsForList();
long l = listOps.rightPushAll(key, v);
if (time > 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
return true;
} catch (Throwable t) {
logger.error("缓存[" + key + "]失败, value[" + v + "]", t);
}
return false;
}

/**
* 缓存list
* @param k
* @param v
* @return
*/
protected boolean cacheList(String k, List<String> v) {
return cacheList(k, v, -1);
}

/**
* 获取list缓存
* @param k
* @param start
* @param end
* @return
*/
protected List<String> getList(String k, long start, long end) {
try {
ListOperations<String, String> listOps =  redisTemplate.opsForList();
return listOps.range(KEY_PREFIX_LIST + k, start, end);
} catch (Throwable t) {
logger.error("获取list缓存失败key[" + KEY_PREFIX_LIST + k + ", error[" + t + "]");
}
return null;
}

/**
* 获取总条数, 可用于分页
* @param k
* @return
*/
protected long getListSize(String k) {
try {
ListOperations<String, String> listOps =  redisTemplate.opsForList();
return listOps.size(KEY_PREFIX_LIST + k);
} catch (Throwable t) {
logger.error("获取list长度失败key[" + KEY_PREFIX_LIST + k + "], error[" + t + "]");
}
return 0;
}

/**
* 获取总条数, 可用于分页
* @param listOps
* @param k
* @return
*/
protected long getListSize(ListOperations<String, String> listOps, String k) {
try {
return listOps.size(KEY_PREFIX_LIST + k);
} catch (Throwable t) {
logger.error("获取list长度失败key[" + KEY_PREFIX_LIST + k + "], error[" + t + "]");
}
return 0;
}

/**
* 移除list缓存
* @param k
* @return
*/
protected boolean removeOneOfList(String k) {
String key = KEY_PREFIX_LIST + k;
try {
ListOperations<String, String> listOps =  redisTemplate.opsForList();
listOps.rightPop(KEY_PREFIX_LIST + k);
return true;
} catch (Throwable t) {
logger.error("移除list缓存失败key[" + KEY_PREFIX_LIST + k + ", error[" + t + "]");
}
return false;
}
}


以上就是对redis的操作工具实现了,学习笔记over
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息