SpringMVC Cache注解+Redis


依賴jar包:
Xml代碼  收藏代碼

    <!-- redis -->  
            <dependency>  
                <groupId>org.springframework.data</groupId>  
                <artifactId>spring-data-redis</artifactId>  
                <version>1.3.4.RELEASE</version>  
            </dependency>  
      
            <dependency>  
                <groupId>redis.clients</groupId>  
                <artifactId>jedis</artifactId>  
                <version>2.5.2</version>  
            </dependency>  

 applicationContext-cache-redis.xml

 
Xml代碼  收藏代碼

    <context:property-placeholder  
            location="classpath:/config/properties/redis.properties" />  
      
        <!-- 啟用緩存注解功能,這個是必須的,否則注解不會生效,另外,該注解一定要聲明在spring主配置文件中才會生效 -->  
        <cache:annotation-driven cache-manager="cacheManager" />  
      
        <!-- spring自己的換管理器,這里定義了兩個緩存位置名稱 ,既注解中的value -->  
        <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">  
            <property name="caches">  
                <set>  
                    <bean class="org.cpframework.cache.redis.RedisCache">  
                        <property name="redisTemplate" ref="redisTemplate" />  
                        <property name="name" value="default"/>  
                    </bean>  
                    <bean class="org.cpframework.cache.redis.RedisCache">  
                        <property name="redisTemplate" ref="redisTemplate02" />  
                        <property name="name" value="commonCache"/>  
                    </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: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:pool-config-ref="poolConfig"  
            p:database="${redis.database}" />  
      
        <bean id="redisTemplate02" class="org.springframework.data.redis.core.RedisTemplate">  
            <property name="connectionFactory" ref="connectionFactory02" />  
        </bean>  

redis.properties

 
Java代碼  收藏代碼

    # Redis settings    
    # server IP  
    redis.host=192.168.xx.xx  
    # server port  
    redis.port=6379     
    # 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

 
Java代碼  收藏代碼

    package org.cpframework.cache.redis;  
      
    import java.io.ByteArrayInputStream;  
    import java.io.ByteArrayOutputStream;  
    import java.io.IOException;  
    import java.io.ObjectInputStream;  
    import java.io.ObjectOutputStream;  
      
    import org.springframework.cache.Cache;  
    import org.springframework.cache.support.SimpleValueWrapper;  
    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;  
      
      
    public class RedisCache implements Cache {  
      
        private RedisTemplate<String, Object> redisTemplate;  
        private String name;  
      
        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() {  
            // TODO Auto-generated method stub  
            return this.name;  
        }  
      
        @Override  
        public Object getNativeCache() {  
            // TODO Auto-generated method stub  
            return this.redisTemplate;  
        }  
      
        @Override  
        public ValueWrapper get(Object key) {  
            // TODO Auto-generated method stub  
            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);  
                    if (value == null) {  
                        return null;  
                    }  
                    return toObject(value);  
      
                }  
            });  
            return (object != null ? new SimpleValueWrapper(object) : null);  
        }  
      
        @Override  
        public void put(Object key, Object value) {  
            // TODO Auto-generated method stub  
            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);  
                    if (liveTime > 0) {  
                        connection.expire(keyb, liveTime);  
                    }  
                    return 1L;  
                }  
            });  
        }  
      
        /**
         * 描述 : <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;  
        }  
      
        @Override  
        public void evict(Object key) {  
            // TODO Auto-generated method stub  
            final String keyf = (String) key;  
            redisTemplate.execute(new RedisCallback<Long>() {  
                public Long doInRedis(RedisConnection connection)  
                        throws DataAccessException {  
                    return connection.del(keyf.getBytes());  
                }  
            });  
        }  
      
        @Override  
        public void clear() {  
            // TODO Auto-generated method stub  
            redisTemplate.execute(new RedisCallback<String>() {  
                public String doInRedis(RedisConnection connection)  
                        throws DataAccessException {  
                    connection.flushDb();  
                    return "ok";  
                }  
            });  
        }  
      
    }


免責聲明!

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



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