Spring整合Redis(spring-data-redis)
本文内容纲要:
历经几天看了大量的博客资料,差不多算是搞定了,目前只是针对单个数据源,集群暂时没研究
maven依赖
<properties>
<!--redis版本-->
<redis.version>2.9.0</redis.version>
<spring.redis.version>1.8.4.RELEASE</spring.redis.version>
</properties>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${redis.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${spring.redis.version}</version>
</dependency>
redis.properties
redis.host=127.0.0.1
redis.port=6379
redis.password=""
redis.maxIdle=400
redis.maxTotal=6000
redis.maxWaitMillis=1000
redis.blockWhenExhausted=true
redis.testOnBorrow=true
redis.timeout=100000
defaultCacheExpireTime=60
spring-redis.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd"
default-lazy-init="false">
<!--加载配置文件-->
<context:property-placeholderlocation="classpath:redis.properties"/>
<!--redis数据源-->
<beanid="poolConfig"class="redis.clients.jedis.JedisPoolConfig">
<!--最大空闲数-->
<propertyname="maxIdle"value="${redis.maxIdle}"/>
<!--最大空连接数-->
<propertyname="maxTotal"value="${redis.maxTotal}"/>
<!--最大等待时间-->
<propertyname="maxWaitMillis"value="${redis.maxWaitMillis}"/>
<!--连接超时时是否阻塞,false时报异常,ture阻塞直到超时,默认true-->
<propertyname="blockWhenExhausted"value="${redis.blockWhenExhausted}"/>
<!--返回连接时,检测连接是否成功-->
<propertyname="testOnBorrow"value="${redis.testOnBorrow}"/>
</bean>
<!--Spring-redis连接池管理工厂-->
<beanid="jedisConnectionFactory"class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<!--IP地址-->
<propertyname="hostName"value="${redis.host}"/>
<!--端口号-->
<propertyname="port"value="${redis.port}"/>
<!--超时时间默认2000-->
<propertyname="timeout"value="${redis.timeout}"/>
<!--连接池配置引用-->
<propertyname="poolConfig"ref="poolConfig"/>
<!--usePool:是否使用连接池-->
<propertyname="usePool"value="true"/>
</bean>
<!--redistemplatedefinition-->
<beanid="redisTemplate"class="org.springframework.data.redis.core.RedisTemplate">
<propertyname="connectionFactory"ref="jedisConnectionFactory"/>
<propertyname="keySerializer">
<beanclass="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<propertyname="valueSerializer">
<beanclass="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
<propertyname="hashKeySerializer">
<beanclass="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<propertyname="hashValueSerializer">
<beanclass="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
<!--开启事务-->
<propertyname="enableTransactionSupport"value="true"></property>
</bean>
<!--自定义redis工具类,在需要缓存的地方注入此类-->
<beanid="redisrCacheManager"class="com.phil.common.redis.RedisCacheManager">
<propertyname="redisTemplate"ref="redisTemplate"/>
</bean>
</beans>
RedisCacheManager.java
packagecom.phil.common.redis;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importjava.util.concurrent.TimeUnit;
importorg.springframework.data.redis.core.RedisTemplate;
importorg.springframework.util.CollectionUtils;
/**
*RedisUtil
*@authorphil
*@date2017年8月14日
*
*/
publicclassRedisCacheManager{
privateRedisTemplate<String,Object>redisTemplate;
publicvoidsetRedisTemplate(RedisTemplate<String,Object>redisTemplate){
this.redisTemplate=redisTemplate;
}
/**
*指定缓存失效时间
*
*@paramkey
*键
*@paramtime
*时间(秒)
*@return
*/
publicbooleanexpire(Stringkey,longtime){
try{
if(time>0){
redisTemplate.expire(key,time,TimeUnit.SECONDS);
}
returntrue;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
}
/**
*根据key获取过期时间
*
*@paramkey
*键不能为null
*@return时间(秒)返回0代表为永久有效
*/
publiclonggetExpire(Stringkey){
returnredisTemplate.getExpire(key,TimeUnit.SECONDS);
}
/**
*判断key是否存在
*
*@paramkey
*键
*@returntrue存在false不存在
*/
publicbooleanhasKey(Stringkey){
try{
returnredisTemplate.hasKey(key);
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
}
/**
*删除缓存
*
*@paramkey
*可以传一个值或多个
*/
@SuppressWarnings("unchecked")
publicvoiddel(String...key){
if(key!=null&&key.length>0){
if(key.length==1){
redisTemplate.delete(key[0]);
}else{
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
//============================String=============================
/**
*普通缓存获取
*
*@paramkey
*键
*@return值
*/
publicObjectget(Stringkey){
returnkey==null?null:redisTemplate.opsForValue().get(key);
}
/**
*普通缓存放入
*
*@paramkey
*键
*@paramvalue
*值
*@returntrue成功false失败
*/
publicbooleanset(Stringkey,Objectvalue){
try{
redisTemplate.opsForValue().set(key,value);
returntrue;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
}
/**
*普通缓存放入并设置时间
*
*@paramkey
*键
*@paramvalue
*值
*@paramtime
*时间(秒)time要大于0如果time小于等于0将设置无限期
*@returntrue成功false失败
*/
publicbooleanset(Stringkey,Objectvalue,longtime){
try{
if(time>0){
redisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);
}else{
set(key,value);
}
returntrue;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
}
/**
*递增
*
*@paramkey
*键
*@paramby
*要增加几(大于0)
*@return
*/
publiclongincr(Stringkey,longdelta){
if(delta<0){
thrownewRuntimeException("递增因子必须大于0");
}
returnredisTemplate.opsForValue().increment(key,delta);
}
/**
*递减
*
*@paramkey
*键
*@paramby
*要减少几(小于0)
*@return
*/
publiclongdecr(Stringkey,longdelta){
if(delta<0){
thrownewRuntimeException("递减因子必须大于0");
}
returnredisTemplate.opsForValue().increment(key,-delta);
}
//================================Map=================================
/**
*HashGet
*
*@paramkey
*键不能为null
*@paramitem
*项不能为null
*@return值
*/
publicObjecthget(Stringkey,Stringitem){
returnredisTemplate.opsForHash().get(key,item);
}
/**
*获取hashKey对应的所有键值
*
*@paramkey
*键
*@return对应的多个键值
*/
publicMap<Object,Object>hmget(Stringkey){
returnredisTemplate.opsForHash().entries(key);
}
/**
*HashSet
*
*@paramkey
*键
*@parammap
*对应多个键值
*@returntrue成功false失败
*/
publicbooleanhmset(Stringkey,Map<String,Object>map){
try{
redisTemplate.opsForHash().putAll(key,map);
returntrue;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
}
/**
*HashSet并设置时间
*
*@paramkey
*键
*@parammap
*对应多个键值
*@paramtime
*时间(秒)
*@returntrue成功false失败
*/
publicbooleanhmset(Stringkey,Map<String,Object>map,longtime){
try{
redisTemplate.opsForHash().putAll(key,map);
if(time>0){
expire(key,time);
}
returntrue;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
}
/**
*向一张hash表中放入数据,如果不存在将创建
*
*@paramkey
*键
*@paramitem
*项
*@paramvalue
*值
*@returntrue成功false失败
*/
publicbooleanhset(Stringkey,Stringitem,Objectvalue){
try{
redisTemplate.opsForHash().put(key,item,value);
returntrue;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
}
/**
*向一张hash表中放入数据,如果不存在将创建
*
*@paramkey
*键
*@paramitem
*项
*@paramvalue
*值
*@paramtime
*时间(秒)注意:如果已存在的hash表有时间,这里将会替换原有的时间
*@returntrue成功false失败
*/
publicbooleanhset(Stringkey,Stringitem,Objectvalue,longtime){
try{
redisTemplate.opsForHash().put(key,item,value);
if(time>0){
expire(key,time);
}
returntrue;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
}
/**
*删除hash表中的值
*
*@paramkey
*键不能为null
*@paramitem
*项可以使多个不能为null
*/
publicvoidhdel(Stringkey,Object...item){
redisTemplate.opsForHash().delete(key,item);
}
/**
*判断hash表中是否有该项的值
*
*@paramkey
*键不能为null
*@paramitem
*项不能为null
*@returntrue存在false不存在
*/
publicbooleanhHasKey(Stringkey,Stringitem){
returnredisTemplate.opsForHash().hasKey(key,item);
}
/**
*hash递增如果不存在,就会创建一个并把新增后的值返回
*
*@paramkey
*键
*@paramitem
*项
*@paramby
*要增加几(大于0)
*@return
*/
publicdoublehincr(Stringkey,Stringitem,doubleby){
returnredisTemplate.opsForHash().increment(key,item,by);
}
/**
*hash递减
*
*@paramkey
*键
*@paramitem
*项
*@paramby
*要减少记(小于0)
*@return
*/
publicdoublehdecr(Stringkey,Stringitem,doubleby){
returnredisTemplate.opsForHash().increment(key,item,-by);
}
//============================set=============================
/**
*根据key获取Set中的所有值
*
*@paramkey
*键
*@return
*/
publicSet<Object>sGet(Stringkey){
try{
returnredisTemplate.opsForSet().members(key);
}catch(Exceptione){
e.printStackTrace();
returnnull;
}
}
/**
*根据value从一个set中查询,是否存在
*
*@paramkey
*键
*@paramvalue
*值
*@returntrue存在false不存在
*/
publicbooleansHasKey(Stringkey,Objectvalue){
try{
returnredisTemplate.opsForSet().isMember(key,value);
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
}
/**
*将数据放入set缓存
*
*@paramkey
*键
*@paramvalues
*值可以是多个
*@return成功个数
*/
publiclongsSet(Stringkey,Object...values){
try{
returnredisTemplate.opsForSet().add(key,values);
}catch(Exceptione){
e.printStackTrace();
return0;
}
}
/**
*将set数据放入缓存
*
*@paramkey
*键
*@paramtime
*时间(秒)
*@paramvalues
*值可以是多个
*@return成功个数
*/
publiclongsSetAndTime(Stringkey,longtime,Object...values){
try{
Longcount=redisTemplate.opsForSet().add(key,values);
if(time>0)
expire(key,time);
returncount;
}catch(Exceptione){
e.printStackTrace();
return0;
}
}
/**
*获取set缓存的长度
*
*@paramkey
*键
*@return
*/
publiclongsGetSetSize(Stringkey){
try{
returnredisTemplate.opsForSet().size(key);
}catch(Exceptione){
e.printStackTrace();
return0;
}
}
/**
*移除值为value的
*
*@paramkey
*键
*@paramvalues
*值可以是多个
*@return移除的个数
*/
publiclongsetRemove(Stringkey,Object...values){
try{
Longcount=redisTemplate.opsForSet().remove(key,values);
returncount;
}catch(Exceptione){
e.printStackTrace();
return0;
}
}
//===============================list=================================
/**
*获取list缓存的内容
*
*@paramkey
*键
*@paramstart
*开始
*@paramend
*结束0到-1代表所有值
*@return
*/
publicList<Object>lGet(Stringkey,longstart,longend){
try{
returnredisTemplate.opsForList().range(key,start,end);
}catch(Exceptione){
e.printStackTrace();
returnnull;
}
}
/**
*获取list缓存的长度
*
*@paramkey
*键
*@return
*/
publiclonglGetListSize(Stringkey){
try{
returnredisTemplate.opsForList().size(key);
}catch(Exceptione){
e.printStackTrace();
return0;
}
}
/**
*通过索引获取list中的值
*
*@paramkey
*键
*@paramindex
*索引index>=0时,0表头,1第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
*@return
*/
publicObjectlGetIndex(Stringkey,longindex){
try{
returnredisTemplate.opsForList().index(key,index);
}catch(Exceptione){
e.printStackTrace();
returnnull;
}
}
/**
*将list放入缓存
*
*@paramkey
*键
*@paramvalue
*值
*@paramtime
*时间(秒)
*@return
*/
publicbooleanlSet(Stringkey,Objectvalue){
try{
redisTemplate.opsForList().rightPush(key,value);
returntrue;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
}
/**
*将list放入缓存
*
*@paramkey
*键
*@paramvalue
*值
*@paramtime
*时间(秒)
*@return
*/
publicbooleanlSet(Stringkey,Objectvalue,longtime){
try{
redisTemplate.opsForList().rightPush(key,value);
if(time>0)
expire(key,time);
returntrue;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
}
/**
*将list放入缓存
*
*@paramkey
*键
*@paramvalue
*值
*@paramtime
*时间(秒)
*@return
*/
publicbooleanlSet(Stringkey,List<Object>value){
try{
redisTemplate.opsForList().rightPushAll(key,value);
returntrue;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
}
/**
*将list放入缓存
*
*@paramkey
*键
*@paramvalue
*值
*@paramtime
*时间(秒)
*@return
*/
publicbooleanlSet(Stringkey,List<Object>value,longtime){
try{
redisTemplate.opsForList().rightPushAll(key,value);
if(time>0)
expire(key,time);
returntrue;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
}
/**
*根据索引修改list中的某条数据
*
*@paramkey
*键
*@paramindex
*索引
*@paramvalue
*值
*@return
*/
publicbooleanlUpdateIndex(Stringkey,longindex,Objectvalue){
try{
redisTemplate.opsForList().set(key,index,value);
returntrue;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
}
/**
*移除N个值为value
*
*@paramkey
*键
*@paramcount
*移除多少个
*@paramvalue
*值
*@return移除的个数
*/
publiclonglRemove(Stringkey,longcount,Objectvalue){
try{
Longremove=redisTemplate.opsForList().remove(key,count,value);
returnremove;
}catch(Exceptione){
e.printStackTrace();
return0;
}
}
}
实际使用
比如微信的access_token有效期只有2小时,不可能即用即获取
packagecom.phil.common.listener;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.context.ApplicationListener;
importorg.springframework.context.event.ContextRefreshedEvent;
importorg.springframework.stereotype.Component;
importcom.phil.common.config.WechatConfig;
importcom.phil.common.redis.RedisCacheManager;
importcom.phil.common.util.HttpReqUtil;
/**
*初始化生成微信token
*@authorphil
*@date2017年7月9日
*
*/
@Component
publicclassInitWechatAuthListenerimplementsApplicationListener<ContextRefreshedEvent>{
//privatestaticfinalLoggerlogger=Logger.getLogger(InitWechatAuthListener.class);
@Autowired
privateRedisCacheManagerredisCacheManager;
privatestaticbooleanisStart=false;//防止二次调用
@Override
publicvoidonApplicationEvent(ContextRefreshedEventevent){
if(!isStart){
isStart=true;
Stringtoken=HttpReqUtil.getAccessToken(WechatConfig.APP_ID,WechatConfig.APP_SECRET);
redisCacheManager.set("phil_token",token,3600);//1小时
}
}
}
/**
*
*/
packagecom.phil.wechatqrcode.controller;
importorg.springframework.beans.factory.annotation.Autowired;
importcom.phil.common.config.WechatConfig;
importcom.phil.common.redis.RedisCacheManager;
importcom.phil.common.util.HttpReqUtil;
importcom.phil.wechatqrcode.service.WechatQRCodeService;
/**
*微信带参二维码
*@authorphil
*@date2017年7月24日
*
*/
publicclassWechatQRCodeController{
@Autowired
privateWechatQRCodeServicewechatQRCodeService;
@Autowired
privateRedisCacheManagerredisCacheManager;
publicStringtest(){
Objectobject=redisCacheManager.get("phil_token");
if(object==null){
redisCacheManager.set("phil_token",HttpReqUtil.getAccessToken(WechatConfig.APP_ID,WechatConfig.APP_SECRET),3600);
object=redisCacheManager.get("phil_token");
}
wechatQRCodeService.createForeverStrTicket(object.toString(),"123");
returnnull;
}
}
以上只是个示例,自己视情况改写和重新封装
本文内容总结:
原文链接:https://www.cnblogs.com/phil_jing/p/7468586.html