近来项目需要redis作为缓存系统,爬了好多坑,特此纪念
首先 pom.xml
<!--整合Redis-->
<!--需要注意导入依赖的版本一定要匹配-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.4.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.6.2</version>
</dependency>
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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- scanner redis properties -->
<context:property-placeholder location="classpath:config.properties"/>
<!--(1)如果你有多个数据源需要通过<context:property-placeholder管理,且不愿意放在一个配置文件里,那么一定要加上ignore-unresolvable=“true"-->
<!--(2)注意新版的(具体从哪个版本开始不清楚,有兴趣可以查一下)JedisPoolConfig的property name,不是maxActive而是maxTotal,而且没有maxWait属性,建议看一下Jedis源码。-->
<!-- redis连接池 -->
<bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.maxActive}"></property>
<property name="maxIdle" value="${redis.maxIdle}"></property>
<property name="maxWaitMillis" value="${redis.maxWait}"></property>
<property name="testOnBorrow" value="${redis.testOnBorrow}"></property>
</bean>
<!-- redis连接工厂 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}"></property>
<property name="port" value="${redis.port}"></property>
<property name="password" value="${redis.pass}"></property>
<property name="poolConfig" ref="jedisConfig"></property>
</bean>
<!-- redis操作模板,这里采用尽量面向对象的模板 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
<!-- 如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 can't cast to String!!!-->
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
</bean>
</beans>
config.properties
#redis绑定的主机地址
redis.host=127.0.0.1
#redis监听端口,默认6379
redis.port=6379
#redis授权密码
redis.pass=
#最大空闲数,空闲链接数大于maxIdle时,将进行回收
redis.maxIdle=100
#最大连接数,能够同时建立的“最大链接个数”
redis.maxActive=300
#最大等待时间:单位ms
redis.maxWait=1000
#使用连接时,检测连接是否成功
redis.testOnBorrow=true
#当客户端闲置多长时间后关闭连接,如果指定为0,表示关闭该功能
redis.timeout=10000
RedisUtil.java
只做了简单的方法 string和list
public class RedisUtil {
//https://blog.csdn.net/javaxiaibai0414/article/details/88666453
private static RedisUtil redisUtil = new RedisUtil();
private static RedisTemplate client = null; //连接池自动管理,提供了一个高度封装的“RedisTemplate”类
private static synchronized RedisTemplate getRedisUtil() {
if(client == null){
client = SpringContextHolder.getBean("redisTemplate");
}
return client;
}
private RedisUtil() {}
/**
* 获取唯一实例.
* @return
*/
public static RedisUtil getInstance() {
if(redisUtil == null){
synchronized (RedisUtil.class) {
redisUtil = new RedisUtil();
}
}
return redisUtil;
}
//-------------------------------------------------
//------------------通用操作工具方法----------------
/**
* 指定缓存失效时间
* @param key
* @param time 时间 秒
* @return
*/
public boolean expire(String key,long time){
try{
if(time>0){
getRedisUtil().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 getRedisUtil().getExpire(key);
}
/**
* 判断key是否存在
* @param key
* @return
*/
public boolean hasKey(String key){
try{
return getRedisUtil().hasKey(key);
}catch (Exception e){
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
* @param key 可以穿一个值或多个
*/
@SuppressWarnings("unchecked")
public void del(String ... key){
if(key!=null&&key.length>0){
if (key.length ==1) {
getRedisUtil().delete(key[0]);
}else {
getRedisUtil().delete(CollectionUtils.arrayToList(key));
}
}
}
//-------------------------------------------------
//------------------String类型相关操作方法----------
/**
* 获取缓存
* @param key
* @return
*/
public Object get(String key) {
return key==null?null:getRedisUtil().opsForValue().get(key);
}
/**
* 设置缓存 不设置过期时间(默认永久有效)
* @param key
* @param value
* @return T成功 F失败
*/
public boolean set(String key ,String value) {
try{
getRedisUtil().opsForValue().set(key,value);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
/**
* 设置缓存并设置过期时间 --一般用于token
* @param key
* @param value
* @param time time要大于0 反之则设置为无限期
* @return
*/
public boolean set(String key,String value,long time){
try {
if (time>0){
getRedisUtil().opsForValue().set(key,value,time,TimeUnit.SECONDS);
}else {
set(key,value);
}
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
/**
* 递增
* @param key
* @param delta
* @return
*/
public long incr(String key,long delta){
if(delta<0){
throw new RuntimeException("递增因子必须大于0");
}
return getRedisUtil().opsForValue().increment(key,delta);
}
/**
* 递减
* @param key
* @param delta
* @return
*/
public long decr(String key,long delta){
if(delta<0){
throw new RuntimeException("递增因子必须大于0");
}
return getRedisUtil().opsForValue().increment(key,-delta);
}
//-------------------------------------------------
//------------------LIST类型相关操作方法------------
/**
* 获取list缓存的内容
* @param key
* @param start 开始
* @param end 结束 0到-1代表返回所有
* @return
*/
public List<Object> lGet(String key,long start,long end){
try{
return getRedisUtil().opsForList().range(key,start,end);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
* @param key
* @return
*/
public long lGetListSize(String key){
try {
return getRedisUtil().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 lGetIndex(String key,long index){
try {
return getRedisUtil().opsForList().index(key,index);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存 永久有效
* @param key
* @param value
* @return
*/
public boolean lSet(String key, Object value){
try {
getRedisUtil().opsForList().rightPush(key,value);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存并设置过期时间
* @param key
* @param value
* @param time
* @return
*/
public boolean lSet(String key, Object value ,long time){
try {
getRedisUtil().opsForList().rightPush(key,value);
if (time>0){
expire(key,time);
}
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存 永久有效
* @param key
* @param value
* @return
*/
public boolean lSet(String key, List<Object> value){
try {
getRedisUtil().opsForList().rightPushAll(key,value);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存并设置过期时间
* @param key
* @param value
* @param time
* @return
*/
public boolean lSet(String key, List<Object> value ,long time){
try {
getRedisUtil().opsForList().rightPushAll(key,value);
if (time>0){
expire(key,time);
}
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
}
后记:一定要注意spring-data-redis 和 jedis的版本(这里使用的spring-data-redis 1.4.2和jedis 2.62),这俩货的版本要求太严格了,我项目还是使用spring4 ,本来想升级5结果错误太多放弃了,升级spring5后应该版本问题会好很多