Spring 整合 redis 集群 jar

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);
    }
    
}

 

posted @ 2017-06-29 16:50  lyhappyday  阅读(1592)  评论(0编辑  收藏  举报