springMVC4.X 配置 redis (jar依賴版本問題詳解)



1.首先是安裝redis; 可以去這里(https://github.com/MicrosoftArchive/redis)下載你對應機型的版本.

2.下面就是給工程里添加依賴,每次都說找不到<java.lang.ClassNotFoundException: org.apache.commons.pool2.impl.GenericObjectPoolConfig>,這個是最坑最坑的!我搞的時候我把每個版本下下來,搞了大半天.還是沒搞定.最后貼上版本對應ok的幾個jar依賴,按照這個去下載添加就好了.

jedis-2.1.0.jar

spring-data-redis-1.0.2.RELEASE.jar

只引入這兩個的話,估計也會報上面的那個錯,所以下面的兩個也要引入

commons-pool-1.5.5.jar

commons-pool2-2.2.jar

3.創建redis.properties

#訪問地址  
redis_addr=192.168.1.254  
#訪問端口  
redis_port=6379  
#授權密碼,有沒有這一項取決於要連接的redis服務是否設置了此項  
redis_auth=test123  
#連接池的最大數據庫連接數。設為0表示無限制  
redis_max_active=1024  
#最大空閑數,數據庫連接的最大空閑時間。超過空閑時間,數據庫連接將被標記為不可用,然后被釋放。設為0表示無限制。  
redis_max_idle=200  
#最大建立連接等待時間。如果超過此時間將接到異常。設為-1表示無限制。  
redis_max_wait=10000  
#在borrow一個jedis實例時,是否提前進行alidate操作;如果為true,則得到的jedis實例均是可用的;  
redis_test_on_borrow=true

4.創建spring-redis.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.3.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd ">

	<!-- redis配置 -->
	<context:component-scan base-package="com.deity.robot.redis.daos.*" />
	<!-- redis連接池 -->
	<bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig"> 
		<property name="maxActive" value="${redis_max_active}"></property>
		<property name="maxIdle" value="${redis_max_idle}"></property>
		<property name="maxWait" value="${redis_max_wait}"></property>
		<property name="testOnBorrow" value="${redis_test_on_borrow}"></property>
	</bean>
	<!-- redis連接工廠 -->
	<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<property name="hostName" value="${redis_addr}"></property>
		<property name="port" value="${redis_port}"></property>
		<!-- <property name="password" value="${redis_auth}"></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>

  

5.寫入redisTemplelate實現類,接口文件省略.

@Service("RedisService")
public class RedisServiceImpl implements RedisService{
    
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 寫入緩存
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /*@Override
    public boolean mset(String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }*/
    
    /**
     * 寫入緩存設置時效時間
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 批量刪除對應的value
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量刪除key
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }
    /**
     * 刪除對應的value
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }
    /**
     * 判斷緩存中是否有對應的value
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    /**
     * 讀取緩存
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
    /**
     * 哈希 添加
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value){
        HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
        hash.put(key,hashKey,value);
    }

    /**
     * 哈希獲取數據
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey){
        HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
        return hash.get(key,hashKey);
    }

    /**
     * 列表添加
     * @param k
     * @param v
     */
    public void lPush(String k,Object v){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k,v);
    }

    /**
     * 列表獲取
     * @param k
     * @param l
     * @param l1
     * @return
     */
    public List<Object> lRange(String k, long l, long l1){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k,l,l1);
    }

    /**
     * 集合添加
     * @param key
     * @param value
     */
    public void add(String key,Object value){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key,value);
    }

    /**
     * 集合獲取
     * @param key
     * @return
     */
    public Set<Object> setMembers(String key){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 有序集合添加
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key,Object value,double scoure){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key,value,scoure);
    }

    /**
     * 有序集合獲取
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<Object> rangeByScore(String key,double scoure,double scoure1){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }
    
}

6.其實后面的都不重要,隨便都可以搞出來,最麻煩的就是各個jar依賴的版本沖突和版本的一些其他問題.只要做好第二步,其他的都就正常了.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM