1.maven依赖
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.6.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2.spring整合配置
<!-- redis数据源 -->
<!-- 加载配置文件 -->
<context:property-placeholder location="/WEB-INF/config/redis.properties"/>
<bean id="poolConfig" 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="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<!-- IP地址 -->
<property name="hostName" value="${redis.host}"/>
<!-- 指定db -->
<property name="database" value="${redis.database}"/>
<!-- 端口号 -->
<property name="port" value="${redis.port}"/>
<!-- 超时时间 默认2000-->
<property name="timeout" value="${redis.timeout}"/>
<!-- 连接池配置引用 -->
<property name="poolConfig" ref="poolConfig"/>
<!-- usePool:是否使用连接池 -->
<property name="usePool" value="true"/>
</bean>
<!-- redis template definition -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"/>
<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>
<!--开启事务 -->
<property name="enableTransactionSupport" value="true"></property>
</bean>
<!--自定义redis工具类,在需要缓存的地方注入此类 -->
<bean id="redisrCacheManager" class="hotkidclub.redis.RedisCacheManager">
<property name="redisTemplate" ref="redisTemplate"/>
</bean>
redis数据库链接参数:redis.propertiesr
#本地/测试服host redis.host=127.0.0.1 #dev服密码 redis.password= #指定数据库 redis.database=1 redis.port=6379 redis.maxIdle=50 redis.maxTotal=100 redis.maxWaitMillis=1000 redis.blockWhenExhausted=true redis.testOnBorrow=true redis.timeout=3000 defaultCacheExpireTime=60
3. Redis 工具类 : 封装redis缓存操作API
package hotkidclub.redis;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Redis 工具类 : 封装redis缓存操作API
* <p>
* 1.操作value为String
* <p>
* 2.操作value为Map
* <p>
* 2.操作value为list
* <p>
* 2.操作value为set
* <p>
*
* @date 2020.02.06
*/
public class RedisCacheManager {
private RedisTemplate<String, Object> redisTemplate;
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean ifHasKey(String key) {
try {
return redisTemplate.hasKey(key);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
*
* @param key 键-支持多个string参数:str1,str2,str3...
*/
@SuppressWarnings("unchecked")
public void dellete(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
}
else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
/**
* value type=String : API
*/
/**
* 获取缓存
*
* @param key 键
* @return 值
*/
public Object getStr(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 放入缓存
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean setStr(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean setStrAttachTime(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}
else {
setStr(key, value);
}
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增:将键的整数值增加1
*
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减 : 将键的整数值减1
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
/**
* 2.value type=Map : API
*/
/**
* 获取存储在指定键的哈希字段的值 : Map中某个key的value
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取存储在指定键的哈希中的所有字段和值 :返回map集合
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> getMap(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* 放入缓存 : 放入Map
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean setMap(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 放入缓存,并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean setMapAttachTime(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向key对应的Map中put键值
*
* @param key 键
* @param hashKey 项
* @param value 值
* @return true 成功 false失败
*/
public boolean put(String key, String hashKey, Object value) {
try {
redisTemplate.opsForHash().put(key, hashKey, value);
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向Map中put键值-附带时间
*
* @param key 键
* @param hashKey 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean putAttachTime(String key, String hashKey, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, hashKey, value);
if (time > 0) {
expire(key, time);
}
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除Map中指定key的值
*
* @param key 键 不能为null
* @param item 项 表示可以传入多个Map的kek,用','隔开,或用数组传值 不能为null
*/
public void deleteMap(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断Map中是否有key值
*
* @param key 键 不能为null
* @param hashKey 项 不能为null
* @return true 存在 false不存在
*/
public boolean mapHasKey(String key, String hashKey) {
return redisTemplate.opsForHash().hasKey(key, hashKey);
}
/**
* value type=list : API
*/
/**
* 获取list缓存的内容:根据index区间
*
* @param key 键
* @param startIndex 开始角标
* @param endIndex 结束角标 0 到 -1代表所有值
* @return
*/
public List<Object> getRangeIndex(String key, long startIndex, long endIndex) {
try {
return redisTemplate.opsForList().range(key, startIndex, endIndex);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public long getListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
}
catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object getIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存: 将数据从右向左(尾部)存压栈 / 将数据从左向右(头部)存压栈
*
* @param key 键
* @param value 值
* @param sortType 值 1右 /2 左
* @return
*/
public boolean setListFromRL(String key, Object value, Integer sortType) {
if (sortType == 1) {
redisTemplate.opsForList().rightPush(key, value);
}
else {
redisTemplate.opsForList().leftPush(key, value);
}
try {
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存: 将数据从右向左(尾部)存压栈 / 将数据从左向右(头部)存压栈
*
* @param key 键
* @param value 值
* @param sortType 值 1右 /2 左
* @return
*/
public boolean setListFromRLAttachTime(String key, Object value, Integer sortType, long time) {
if (sortType == 1) {
redisTemplate.opsForList().rightPush(key, value);
}
else {
redisTemplate.opsForList().leftPush(key, value);
}
try {
if (time > 0)
expire(key, time);
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存: 将数据从右向左(尾部)存压栈 / 将数据从左向右(头部)存压栈
*
* @param key 键
* @param value 值
* @param sortType 值 1右 /2 左
* @return
*/
public boolean setListAllFromRL(String key, Object value, Integer sortType) {
if (sortType == 1) {
redisTemplate.opsForList().rightPushAll(key, value);
}
else {
redisTemplate.opsForList().leftPushAll(key, value);
}
try {
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存: 将数据从右向左(尾部)存压栈 / 将数据从左向右(头部)存压栈
*
* @param key 键
* @param value 值
* @param sortType 值 1右 /2 左
* @return
*/
public boolean setListAllFromRLAttachTime(String key, Object value, Integer sortType, long time) {
if (sortType == 1) {
redisTemplate.opsForList().rightPushAll(key, value);
}
else {
redisTemplate.opsForList().leftPushAll(key, value);
}
try {
if (time > 0) {
expire(key, time);
}
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean listUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long listRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
}
catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* value type=set : API
*/
/**
* 根据key获取Set中的所有值
*
* @param key 键
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
}
catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
}
catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
}
catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
}
catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
来源:CSDN
作者:Aron锅
链接:https://blog.csdn.net/weixin_37794901/article/details/104059442