依赖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";  
                }  
            });  
        }  
      
    }

SpringMVC Cache注解+Redis的更多相关文章

  1. springboot 用redis缓存整合spring cache注解,使用Json序列化和反序列化。

    springboot下用cache注解整合redis并使用json序列化反序列化. cache注解整合redis 最近发现spring的注解用起来真的是很方便.随即产生了能不能吧spring注解使用r ...

  2. 十二:SpringBoot-基于Cache注解模式,管理Redis缓存

    SpringBoot-基于Cache注解模式,管理Redis缓存 1.Cache缓存简介 2.核心API说明 3.SpringBoot整合Cache 3.1 核心依赖 3.2 Cache缓存配置 3. ...

  3. SpringBoot2.0 基础案例(13):基于Cache注解模式,管理Redis缓存

    本文源码 GitHub地址:知了一笑 https://github.com/cicadasmile/spring-boot-base 一.Cache缓存简介 从Spring3开始定义Cache和Cac ...

  4. springMVC+Spring+Mybatis+Redis

    SPRINGMVC+MYBATIS+SPRING+REDIS 只作参考,以防忘记使用! mybatis的配置文件: <?xml version="1.0" encoding= ...

  5. SpringMVC常用注解實例詳解3:@ResponseBody

    我的開發環境框架:        springmvc+spring+freemarker開發工具: springsource-tool-suite-2.9.0JDK版本: 1.6.0_29tomcat ...

  6. SpringMVC + Spring + Mybatis+ Redis +shiro以及MyBatis学习

    SpringMVC + Spring + Mybatis+ Redis +shiro http://www.sojson.com/shiro MyBatis简介与配置MyBatis+Spring+My ...

  7. springboot学习笔记-4 整合Druid数据源和使用@Cache简化redis配置

    一.整合Druid数据源 Druid是一个关系型数据库连接池,是阿里巴巴的一个开源项目,Druid在监控,可扩展性,稳定性和性能方面具有比较明显的优势.通过Druid提供的监控功能,可以实时观察数据库 ...

  8. springboot整合redis-sentinel支持Cache注解

    一.前提 已经存在一个redis-sentinel集群,两个哨兵分别如下: /home/redis-sentinel-cluster/sentinel-1.conf port 26379 dir &q ...

  9. 【Spring】17、spring cache 与redis缓存整合

    spring cache,基本能够满足一般应用对缓存的需求,但现实总是很复杂,当你的用户量上去或者性能跟不上,总需要进行扩展,这个时候你或许对其提供的内存缓存不满意了,因为其不支持高可用性,也不具备持 ...

随机推荐

  1. Codeforces Round #198 (Div. 1) B,C 动态规划

    比赛时,开了大号去做,算了半天发现不会做A,囧.于是跑去看B,发现很水?于是很快敲完了,但是A不会,没敢交.于是去看C,一直找规律啊,后来总算调了出来,看了一下榜,发现还是算了吧,直接去睡觉了.第二天 ...

  2. MVC中Jqgrid的用法

    Jqgrid可以接受的数据源格式通常是local.json.string等,而我们通过MVC Controller查询数据库(Linq)通常转化为tolist(),例如: public object ...

  3. list笔记总结

    1.list是一个复合的复制函数,可以将一个数组一次赋给多个变量.我们常用以下语句遍历一个数组. $arr = array('东','男','西','北'); while(list($k,$v)=ea ...

  4. 【转】Ajax 基础学习

    今天简单的学习了 Ajax 的基础知识,总结在这里.部分代码不是原创,特此说明. [Ajax 简介] AJAX = Asynchronous JavaScript and XML(异步的 JavaSc ...

  5. JSP之邮箱检验

    首先创建Email类继承Serializable接口以启用其序列化功能,而序列化又是为了保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性.序列化接口没有方法或字段,仅用于标识可序列化的语义. ...

  6. Git 一些错误的解决方法

    Git初学者的个人经验记录,仅供参考 1. Pull is not possible because you have unmerged files. 症状:pull的时候 $ git pull Pu ...

  7. php中magic_quotes_gpc对unserialize的影响

    昨天朋友让我帮他解决下他网站的购物车程序的问题,程序用的是PHPCMS,换空间前是好的(刚换的空间),具体问题是提示成功加入购物车后跳转到购物车页面,购物车里为空. 我看了下代码,大致的原理就是将产品 ...

  8. UI1_UISlider与UISegment

    // // ViewController.m // UI1_UISlider与UISegment // // Created by zhangxueming on 15/7/7. // Copyrig ...

  9. AMQ学习笔记 - 11. Spring-JmsTemplate之执行

    概述 前面我们分别介绍了发送.接收和浏览,这三个的实现都依赖于将要介绍的执行. 执行算是一个相对比较底层的方法系列,一般情况下,我们不需要直接面向将要介绍的方法. 执行 1.关于回调接口 在讲执行之前 ...

  10. (转)Linux概念架构的理解

    英文原文:Conceptual Architecture of the Linux Kernel 摘要 Linux kernel成功的两个原因:(1)架构设计支持大量的志愿开发者加入到开发过程中:(2 ...