参考的博客:http://www.cnblogs.com/fengzheng/p/5941953.html
看之前,建议先花点时间去看下jedis的使用。
项目目录如下:
依赖的架包(pom.xml配置):
<!-- spring redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.7.RELEASE</version>
</dependency>
<!-- jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
redis.properties资源文件如下:
#地址,端口号,密码
redis.host=
redis.port=
redis.pass=
#最大空闲数
redis.maxIdle=300
#最大连接数
redis.maxTotal=600
#最大建立连接等待时间
redis.maxWaitMillis=1000
#指明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
redis.testOnBorrow=true
由于我的*.properties文件已经在applicationContext-dao.xml中加载过了,所以这里就不需要重新加载了。
applicationContext-dao.xml中的资源文件加载
<!-- 加载资源文件 -->
<context:property-placeholder ignore-resource-not-found="true" location="classpath:conf/*.properties"/>
spring的redis配置(我的文件名称:applicationContext-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:tx="http://www.springframework.org/schema/tx"
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.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- redis.properties已在applicationContext-dao.xml加载 -->
<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}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.host}"
p:port="${redis.port}"
p:password="${redis.pass}"
p:pool-config-ref="poolConfig"/>
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
</beans>
web.xml配置,项目运行时,加载配置文件
<!-- 容器创建项目运行环境时的配置文件路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
实体类:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.service.redis.RedisService;
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 添加
*/
public void put(String key, Object value) {
put(key, value, null);
}
/**
* 添加
*/
public void put(String key, Object value, Long expiredTime) {
if(StringUtils.isBlank(key)) {
return;
}
if (null == value) {
return;
}
redisTemplate.execute(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection conn) throws DataAccessException {
byte[] keyb = key.getBytes();
byte[] valueb = toByteArray(value);
conn.set(keyb, valueb);
if (null != expiredTime) {
conn.expire(keyb, expiredTime);
// 以下方法我没有亲测,所以使用时请先测试下哈。我只是根据jedis里推断出来的,应该是对jedis里的方法的进行了封装。
// conn.expire(key, seconds) // 多少秒后过期
// conn.expireAt(key, unixTime) // 在什么时候过期,即:System.currentTimeMillis()/1000 + 多少s
// conn.pExpire(key, millis) // 多少毫秒后过期
// conn.pExpireAt(key, unixTimeInMillis) // 在什么时候过期,即:System.currentTimeMillis() + 多少ms
}
return 1l;
}
});
}
/**
* 获取
*/
public Object get(String key) {
Object value;
value = redisTemplate.execute(new RedisCallback<Object>() {
@Override
public Object doInRedis(RedisConnection conn) throws DataAccessException {
byte[] keyb = key.getBytes();
byte[] valueb = conn.get(keyb);
return toObject(valueb);
}
});
return value;
}
/**
* 将byte[] 转成 Object
*
* @param bytes
* @return
*/
private Object toObject(byte[] bytes) {
Object obj = null;
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
obj = ois.readObject();
} catch(IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
ois.close();
bais.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return obj;
}
/**
* object 转成 byte[]
* @param obj
* @return
*/
private byte[] toByteArray(Object obj) {
byte[] bytes = null;
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.flush();
bytes = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
oos.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bytes;
}
}
需要注意的是,RedisService中的put(),get()是配套的。因为保存value时通过输出流将value值序列化了,所以需要通过输入流进行反序列化才能取出。
比如保存value值未通过输出流直接将值存入,然后用get()直接取是会报java.io.StreamCorruptedException错误。