依赖jar包:
<!-- config redis data and client jar--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.6.4.RELEASE</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.1</version> </dependency>
applicationContext-cache-redis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd" default-autowire="byName"> <context:property-placeholder location="classpath*:redis/redis.properties" ignore-unresolvable="true" /> <!-- 启用缓存注解功能,这个是必须的,否则注解不会生效,另外,该注解一定要声明在spring主配置文件中才会生效 --> <cache:annotation-driven cache-manager="cacheManager" /> <!-- spring自己的换管理器,这里定义了两个缓存位置名称 ,既注解中的value --> <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"> <property name="caches"> <set> <bean class="com.xncredit.base.redis.RedisCache"> <property name="redisTemplate" ref="redisTemplate" /> <property name="name" value="default" /> </bean> <bean class="com.xncredit.base.redis.RedisCache"> <property name="redisTemplate" ref="redisTemplate" /> <property name="name" value="UserCache" /> </bean> </set> </property> </bean> <!-- redis 相关配置 --> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="${redis.maxIdle}" /> <property name="maxWaitMillis" value="${redis.maxWait}" /> <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.pwd}" p:pool-config-ref="poolConfig" p:database="${redis.database}" /> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="connectionFactory" /> </bean> <bean id="connectionFactory02" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pwd}" p:pool-config-ref="poolConfig" p:database="${redis.database}" /> <bean id="redisTemplate02" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="connectionFactory02" /> </bean> </beans>
redis.properties
# Redis settings # server IP redis.host=192.168.xx.xx # server port redis.port=6379 # server password redis.pwd=123456 # use dbIndex redis.database=0 # 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例 redis.maxIdle=300 # 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间(毫秒),则直接抛出JedisConnectionException; redis.maxWait=3000 # 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的 redis.testOnBorrow=true
RedisCache.java
package com.xncredit.base.redis; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Set; import org.apache.shiro.dao.DataAccessException; import org.springframework.cache.Cache; import org.springframework.cache.support.SimpleValueWrapper; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; /** * * @author WangYaL 邮箱:[email protected] * @dateTime 2016年10月18日 下午3:32:17 */ public class RedisCache implements Cache { private String name; private RedisTemplate<String, Object> redisTemplate; public RedisTemplate<String, Object> getRedisTemplate() { return redisTemplate; } public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } public void setName(String name) { this.name = name; } @Override public String getName() { return this.name; } @Override public Object getNativeCache() { return this.redisTemplate; } @Override public ValueWrapper get(Object key) { final String keyf = (String) key; Object object = null; object = redisTemplate.execute(new RedisCallback<Object>() { public Object doInRedis(RedisConnection connection) throws DataAccessException { byte[] key = keyf.getBytes(); // byte[] value = connection.get(key); byte[] t = name.getBytes(); byte[] value = connection.hGet(t, key); if (value == null) { return null; } return toObject(value); } }); return (object != null ? new SimpleValueWrapper(object) : null); } @Override public <T> T get(Object key, Class<T> type) { // TODO Auto-generated method stub return null; } @Override public void put(Object key, Object value) { final String keyf = (String) key; final Object valuef = value; final long liveTime = 86400; redisTemplate.execute(new RedisCallback<Long>() { public Long doInRedis(RedisConnection connection) throws DataAccessException { byte[] keyb = keyf.getBytes(); byte[] valueb = toByteArray(valuef); // connection.set(keyb, valueb); byte[] t = name.getBytes(); connection.hSet(t, keyb, valueb); if (liveTime > 0) { connection.expire(keyb, liveTime); } return 1L; } }); } @Override public ValueWrapper putIfAbsent(Object key, Object value) { // TODO Auto-generated method stub return null; } @Override public void evict(Object key) { final String keyf = (String) key; redisTemplate.execute(new RedisCallback<Long>() { public Long doInRedis(RedisConnection connection) throws DataAccessException { // return connection.del(keyf.getBytes()); return connection.hDel(name.getBytes(), keyf.getBytes()); } }); } @Override public void clear() { // 清楚缓存,需要根据Cache的name属性,在redis中模糊查询相关key值的集合,并全部删除 redisTemplate.execute(new RedisCallback<String>() { public String doInRedis(RedisConnection connection) throws DataAccessException { // connection.flushDb(); byte[] t = name.getBytes(); Set<byte[]> fields = connection.hKeys(t); for (byte[] bs : fields) { connection.hDel(t, bs); } return "ok"; } }); } /** * 描述 : <Object转byte[]>. <br> * <p> * <使用方法说明> * </p> * * @param obj * @return */ private byte[] toByteArray(Object obj) { byte[] bytes = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(obj); oos.flush(); bytes = bos.toByteArray(); oos.close(); bos.close(); } catch (IOException ex) { ex.printStackTrace(); } return bytes; } /** * 描述 : <byte[]转Object>. <br> * <p> * <使用方法说明> * </p> * * @param bytes * @return */ private Object toObject(byte[] bytes) { Object obj = null; try { ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bis); obj = ois.readObject(); ois.close(); bis.close(); } catch (IOException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } return obj; } }