spring 版本為:4.1.9.RELEASE
redis.clients : 2.8
spring-data-redis: 1.7.1.RELEASE
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.1.RELEASE</version>
</dependency>
集群配置如下:
<?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:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd" default-lazy-init="true"> <!--引入配置文件--> <context:property-placeholder ignore-unresolvable="true" location="classpath:jeesite.properties" /> <!--配置 jedis pool--> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!-- 最大連接數 --> <property name="maxTotal" value="${redis.cluster.pool.maxTotal}"/> <!-- 最大空閑時間 --> <property name="maxIdle" value="${redis.cluster.pool.maxIdle}"/> <!-- 每次最大連接數 --> <property name="numTestsPerEvictionRun" value="1024"/> <!-- 釋放掃描的掃描間隔 --> <property name="timeBetweenEvictionRunsMillis" value="30000"/> <!-- 連接的最小空閑時間 --> <property name="minEvictableIdleTimeMillis" value="1800000"/> <!-- 連接控歘按時間多久后釋放,當空閑時間>該值且空閑連接>最大空閑連接數時直接釋放 --> <property name="softMinEvictableIdleTimeMillis" value="10000"/> <!-- 獲得鏈接時的最大等待毫秒數,小於0:阻塞不確定時間,默認-1 --> <property name="maxWaitMillis" value="1500"/> <!-- 在獲得鏈接的時候檢查有效性,默認false --> <property name="testOnBorrow" value="true"/> <!-- 在空閑時檢查有效性,默認false --> <property name="testWhileIdle" value="true"/> <!-- 連接耗盡時是否阻塞,false報異常,true阻塞超時 默認:true--> <property name="blockWhenExhausted" value="false"/> </bean> <!--配置RedisClusterConfiguration--> <bean id="redisClusterConfiguration" class="org.springframework.data.redis.connection.RedisClusterConfiguration"> <property name="maxRedirects" value="5"></property> <property name="clusterNodes"> <set> <bean class="org.springframework.data.redis.connection.RedisNode"> <constructor-arg name="host" value="host1" /> <constructor-arg name="port" value="port1" /> </bean> <bean class="org.springframework.data.redis.connection.RedisNode"> <constructor-arg name="host" value="host2" /> <constructor-arg name="port" value="port2" /> </bean> <bean class="org.springframework.data.redis.connection.RedisNode "> <constructor-arg name="host" value="host3" /> <constructor-arg name="port" value="port3" /> </bean> <bean class="org.springframework.data.redis.connection.RedisNode"> <constructor-arg name="host" value="host4" /> <constructor-arg name="port" value="port4" /> </bean>
<bean class="org.springframework.data.redis.connection.RedisNode"> <constructor-arg name="host" value="host5" /> <constructor-arg name="port" value="port5" /> </bean>
<bean class="org.springframework.data.redis.connection.RedisNode"> <constructor-arg name="host" value="host6" /> <constructor-arg name="port" value="port6" /> </bean>
</set> </property> </bean> <!--配置JedisConnectionFactory--> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <constructor-arg name="poolConfig" ref="jedisPoolConfig"/> <constructor-arg name="clusterConfig" ref="redisClusterConfiguration"/> </bean> <!--redisTemplate--> <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> </bean> <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory" /> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> </bean> <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"> <constructor-arg index="0" ref="redisTemplate" /> </bean> <bean id="keyGenerator" class="com.thinkgem.jeesite.common.utils.CacheKeyGenerator" /> </beans>
單點配置如下:
<?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:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd" default-lazy-init="true"> <description>Jedis Configuration</description> <!-- 加載配置屬性文件 --> <context:property-placeholder ignore-unresolvable="true" location="classpath:jeesite.properties" /> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="10" /> <!-- 最大能夠保持idel狀態的對象數 --> <property name="maxTotal" value="30" /> <!-- 最大分配的對象數 --> <property name="testOnBorrow" value="true" /> <!-- 當調用borrow Object方法時,是否進行有效性檢查 --> </bean> <bean id="jedisPool" class="redis.clients.jedis.JedisPool"> <constructor-arg index="0" ref="jedisPoolConfig" /> <constructor-arg index="1" value="${redis.single.host}" type="java.lang.String"/> <constructor-arg index="2" value="${redis.single.port}" type="int" /> </bean> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="poolConfig" ref="jedisPoolConfig" /> <property name="hostName" value="host" /> <property name="port" value="port" /> <property name="database" value="datebasename" /> </bean> <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> </bean> <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory" /> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> </bean> <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"> <constructor-arg index="0" ref="redisTemplate" /> </bean> <bean id="keyGenerator" class="com.thinkgem.jeesite.common.utils.CacheKeyGenerator" /> </beans>
若單點和集群共同使用,則可使用RedisTemplate
import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.BoundHashOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import com.thinkgem.jeesite.common.config.Global; /** * Jedis Cache 工具類 * * @author ThinkGem * @version 2014-6-29 */ public class JedisUtils { private static Logger logger = LoggerFactory.getLogger(JedisUtils.class); public static final String KEY_PREFIX = Global.getConfig("redis.keyPrefix"); private static StringRedisTemplate stringRedisTemplate = SpringContextHolder.getBean("stringRedisTemplate"); private static RedisTemplate<String, Object> redisTemplate = SpringContextHolder.getBean("redisTemplate"); /** * 獲取緩存 * @param key 鍵 * @return 值 */ public static String get(String key) { return stringRedisTemplate.opsForValue().get(key); } /** * 獲取緩存 * @param key 鍵 * @return 值 */ public static Object getObject(String key) { return redisTemplate.opsForValue().get(key); } /** * 設置緩存 * @param key 鍵 * @param value 值 * @param cacheSeconds 超時時間,0為不超時 * @return */ public static void set(String key, String value, int cacheSeconds) { setObj(key, value, cacheSeconds); } /** * 設置緩存 * @param key 鍵 * @param value 值 * @param cacheSeconds 超時時間,0為不超時 * @return */ public static void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } /** * 設置緩存 * @param key 鍵 * @param value 值 * @param cacheSeconds 超時時間,0為不超時 * @return */ public static void setObject(String key, Object value, int cacheSeconds) { setObj(key, value, cacheSeconds); } /** * 將value對象寫入緩存 * @param key * @param value * @param time 失效時間(秒) */ public static void setObj(String key, Object value, int time){ if(value.getClass().equals(String.class)){ stringRedisTemplate.opsForValue().set(key, value.toString()); stringRedisTemplate.opsForValue().getAndSet(key, value.toString()); }else if(value.getClass().equals(Integer.class)){ stringRedisTemplate.opsForValue().set(key, value.toString()); }else if(value.getClass().equals(Double.class)){ stringRedisTemplate.opsForValue().set(key, value.toString()); }else if(value.getClass().equals(Float.class)){ stringRedisTemplate.opsForValue().set(key, value.toString()); }else if(value.getClass().equals(Short.class)){ stringRedisTemplate.opsForValue().set(key, value.toString()); }else if(value.getClass().equals(Long.class)){ stringRedisTemplate.opsForValue().set(key, value.toString()); }else if(value.getClass().equals(Boolean.class)){ stringRedisTemplate.opsForValue().set(key, value.toString()); }else{ redisTemplate.opsForValue().set(key, value); } if(time > 0){ redisTemplate.expire(key, time, TimeUnit.SECONDS); } } /** * 獲取List緩存 * @param key 鍵 * @return 值 */ public static List<String> getList(String key) { return stringRedisTemplate.opsForList().range(key, 0, -1); } /** * 獲取List緩存 * @param key 鍵 * @return 值 */ public static List<Object> getObjectList(String key) { return redisTemplate.opsForList().range(key, 0, -1); } /** * 設置List緩存 * @param key 鍵 * @param value 值 * @param cacheSeconds 超時時間,0為不超時 * @return */ public static long setList(String key, List<String> value, int cacheSeconds) { long result = 0; result = redisTemplate.opsForList().rightPush(key, value); if(cacheSeconds > 0){ redisTemplate.expire(key, cacheSeconds, TimeUnit.SECONDS); } return result; } /** * 設置List緩存 * @param key 鍵 * @param value 值 * @param cacheSeconds 超時時間,0為不超時 * @return */ public static long setObjectList(String key, List<Object> value, int cacheSeconds) { long result = 0; result = redisTemplate.opsForList().rightPushAll(key, value); if(cacheSeconds > 0){ redisTemplate.expire(key, cacheSeconds, TimeUnit.SECONDS); } return result; } /** * 向List緩存中添加值 * @param key 鍵 * @param value 值 * @return */ public static long listAdd(String key, String... value) { long result = 0; result = stringRedisTemplate.opsForList().rightPushAll(key, value); return result; } /** * 向List緩存中添加值 * @param key 鍵 * @param value 值 * @return */ public static long listObjectAdd(String key, Object... value) { long result = 0; result = redisTemplate.opsForList().rightPushAll(key, value); return result; } /** * 獲取緩存 * @param key 鍵 * @return 值 */ public static Set<String> getSet(String key) { Set<String> value = null; value = stringRedisTemplate.opsForSet().members(key); return value; } /** * 獲取緩存 * @param key 鍵 * @return 值 */ public static Set<Object> getObjectSet(String key) { Set<Object> value = null; value = redisTemplate.opsForSet().members(key); return value; } /** * 設置Set緩存 * @param key 鍵 * @param value 值 * @param cacheSeconds 超時時間,0為不超時 * @return */ public static long setSet(String key, Set<String> value, int cacheSeconds) { long result = 0; result = stringRedisTemplate.opsForSet().add(key, (String[])value.toArray()); if(cacheSeconds > 0){ stringRedisTemplate.expire(key, cacheSeconds, TimeUnit.SECONDS); } return result; } /** * 設置Set緩存 * @param key 鍵 * @param value 值 * @param cacheSeconds 超時時間,0為不超時 * @return */ public static long setObjectSet(String key, Set<Object> value, int cacheSeconds) { long result = 0; result = redisTemplate.opsForSet().add(key, value); if(cacheSeconds > 0){ redisTemplate.expire(key, cacheSeconds, TimeUnit.SECONDS); } return result; } /** * 向Set緩存中添加值 * @param key 鍵 * @param value 值 * @return */ public static long setSetAdd(String key, String... value) { long result = 0; result = stringRedisTemplate.opsForSet().add(key, value); return result; } /** * 向Set緩存中添加值 * @param key 鍵 * @param value 值 * @return */ public static long setSetObjectAdd(String key, Object... value) { long result = 0; result = redisTemplate.opsForSet().add(key, value); return result; } /** * 獲取Map緩存 * @param key 鍵 * @return 值 */ public static Map<String, String> getMap(String key) { Map<String, String> value = null; BoundHashOperations<String, String, String> boundHashOperations = redisTemplate.boundHashOps(key); value = boundHashOperations.entries(); return value; } /** * 獲取存儲在指定鍵的哈希字段的值 * @param key, hashKey * @return 值 */ public static Object getMapValueOfKey(String key, Object hashKey) { return redisTemplate.opsForHash().get(key, hashKey); } /** * 獲取Map緩存 * @param key 鍵 * @return 值 */ public static Map<String, Object> getObjectMap(String key) { Map<String, Object> value = null; BoundHashOperations<String, String, Object> boundHashOperations = redisTemplate.boundHashOps(key); value = boundHashOperations.entries(); return value; } /** * 返回map對象中的所有key */ public static Set<Object> getKeysOfMap(String key) { return redisTemplate.opsForHash().keys(key); } /** * 獲取在存儲於 key的散列的所有值 * */ public static List<Object> getValueOfMap(String key) { return redisTemplate.opsForHash().values(key); } /** * 設置Map緩存 * @param key 鍵 * @param value 值 * @param cacheSeconds 超時時間,0為不超時 * @return */ public static void setMap(String key, Map<String, String> value, int cacheSeconds) { redisTemplate.opsForHash().putAll(key, value); if(cacheSeconds > 0){ redisTemplate.expire(key, cacheSeconds, TimeUnit.SECONDS); } } /** * 設置Map緩存 * @param key 鍵 * @param value 值 * @param cacheSeconds 超時時間,0為不超時 * @return */ public static void setObjectMap(String key, Map<String, Object> value, int cacheSeconds) { redisTemplate.opsForHash().putAll(key, value); if(cacheSeconds > 0){ redisTemplate.expire(key, cacheSeconds, TimeUnit.SECONDS); } } /** * 向Map緩存中添加值 * @param key 鍵 * @param value 值 * @return */ public static void mapPut(String key, Map<String, String> value) { redisTemplate.opsForHash().putAll(key, value); } /** * 設置緩存中值為key的map中的hashkey的值為value */ public static void mapPutValue(String key, Object hashKey, Object value) { redisTemplate.opsForHash().put(key, hashKey, value); } /** * 向Map緩存中添加值 * @param key 鍵 * @param value 值 * @return */ public static void mapObjectPut(String key, Map<String, Object> value) { redisTemplate.opsForHash().putAll(key, value); } /** * 移除Map緩存中的值 * @param key 鍵 * @param value 值 * @return */ public static long mapRemove(String key, String mapKey) { long result = 0; result = redisTemplate.opsForHash().delete(key, mapKey); return result; } /** * 移除Map緩存中的值 * @param key 鍵 * @param value 值 * @return */ public static long mapRemove(String key, Object mapKey) { long result = 0; result = redisTemplate.opsForHash().delete(key, mapKey); return result; } /** * 移除Map緩存中的值 * @param key 鍵 * @param value 值 * @return */ public static long mapObjectRemove(String key, String mapKey) { long result = 0; result = redisTemplate.opsForHash().delete(key, mapKey); return result; } /** * 判斷Map緩存中的Key是否存在 * @param key 鍵 * @param value 值 * @return */ public static boolean mapExists(String key, String mapKey) { boolean result = false; result = redisTemplate.opsForHash().hasKey(key, mapKey); return result; } /** * 判斷Map緩存中的Key是否存在 * @param key 鍵 * @param value 值 * @return */ public static boolean mapObjectExists(String key, String mapKey) { boolean result = false; result = redisTemplate.opsForHash().hasKey(key, mapKey); return result; } /** * 刪除緩存 * @param key 鍵 * @return */ public static void del(String key) { redisTemplate.delete(key); } /** * 刪除緩存 * @param key 鍵 * @return */ public static void delObject(String key) { redisTemplate.delete(key); } /** * 緩存是否存在 * @param key 鍵 * @return */ public static boolean exists(String key) { boolean result = false; result = redisTemplate.hasKey(key); return result; } /** * 獲取byte[]類型Key * @param key * @return */ public static byte[] getBytesKey(Object object){ if(object instanceof String){ return StringUtils.getBytes((String)object); }else{ return ObjectUtils.serialize(object); } } /** * 獲取byte[]類型Key * @param key * @return */ public static Object getObjectKey(byte[] key){ try{ return StringUtils.toString(key); }catch(UnsupportedOperationException uoe){ try{ return JedisUtils.toObject(key); }catch(UnsupportedOperationException uoe2){ uoe2.printStackTrace(); } } return null; } /** * Object轉換byte[]類型 * @param key * @return */ public static byte[] toBytes(Object object){ return ObjectUtils.serialize(object); } /** * byte[]型轉換Object * @param key * @return */ public static Object toObject(byte[] bytes){ return ObjectUtils.unserialize(bytes); } /** * 獲得給定map的大小 * */ public static Long size(String key) { return redisTemplate.opsForHash().size(key); } /** * 設置給定key的超時時間 * */ public static void expire(String key, int timeoutSeconds) { redisTemplate.expire(key, timeoutSeconds, TimeUnit.SECONDS); } }