redisCacheManager(redis缓存管理器使用)

@Cacheable、@CachePut、@CacheEvict 注解介绍:
(1)@Cacheable
作用:主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
@Cacheable 主要的参数:
1)value:缓存的名称,在 spring 配置文件中定义,必须指定至少一个
例如:@Cacheable(value=”mycache”) 或者 @Cacheable(value={“cache1”,”cache2”})
2)key:缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合
例如:@Cacheable(value=”testcache”,key=”#userName”)
3)condition:缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存
例如:@Cacheable(value=”testcache”,condition=”#userName.length()>2”)

(2)@CachePut
    作用:主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,
         和@Cacheable不同的是,它每次都会触发真实方法的调用
    @CachePut 主要的参数:同@Cacheable

(3)@CacheEvict
    作用:主要针对方法配置,能够根据一定的条件对缓存进行清空
    @CacheEvict 主要的参数:
        1)value:缓存的名称,在 spring 配置文件中定义,必须指定至少一个
            例如:@CachEvict(value="mycache") 或者 @CachEvict(value={"cache1","cache2"})
        2)key:缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合
            例如:@CachEvict(value="testcache",key="#userName")
        3)condition:缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才清空缓存
            例如:@CachEvict(value="testcache",condition="#userName.length()>2")
        4)allEntries:是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存
            例如:@CachEvict(value="testcache",allEntries=true)
        5)beforeInvocation:是否在方法执行前就清空,缺省为 false,
                             如果指定为 true,则在方法还没有执行的时候就清空缓存,
                             缺省情况下,如果方法执行抛出异常,则不会清空缓存
            例如:@CachEvict(value="testcache”,beforeInvocation=true)

配置+注解的具体使用:

1、pom.xml依赖注入:

            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-redis</artifactId>
                <version>1.7.6.RELEASE</version>
            </dependency>

            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>2.9.0</version>
            </dependency>

2、redis.properties(redis缓存配置文件)

            redis.host=127.0.0.1
            redis.password=123456
            redis.port=6379
            redis.default.db=3  //缓存数据库选择
            redis.timeout=100000
            redis.maxTotal=100
            redis.maxActive=100
            redis.maxIdle=10
            redis.maxWaitMillis=1000
            redis.testOnBorrow=true     //是否在borrow一个jedis之前就validate
            redis.expiration=3600   //缓存数据的最大生命周期,单位:s

3、在spring.xml(servlet-context.xml)中配置jedis以及cacheManager

<!--载入 redis 配置文件-->
<context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/>

        <!-- 开启缓存注解驱动 -->
        <cache:annotation-driven/><!--缺省了cache-manager="cacheManager"-->

        <!-- jedis pool配置 -->
        <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
            <property name="maxTotal" value="${redis.maxTotal}"/>
            <property name="maxIdle" value="${redis.maxIdle}"/>
            <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
            <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
        </bean>

        <!-- spring data redis -->
        <bean id="jedisConnectionFactory"
              class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
              p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.password}"
              p:database="${redis.default.db}"
              p:pool-config-ref="jedisPoolConfig"/>

        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
              p:connectionFactory-ref="jedisConnectionFactory">
            <!--序列化配置-->
            <property name="keySerializer">
                <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
            </property>
            <property name="valueSerializer">
                <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
            </property>
            <property name="hashKeySerializer">
                <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
            </property>
            <property name="hashValueSerializer">
                <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
            </property>
        </bean>


        <!-- 配置cacheManager -->
        <!--使用spring cache--> <!-- simple cache manager -->
        <!--<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
            <property name="caches">
                <set>
                    <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default" />
                    <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="userCache" />
                </set>
            </property>
        </bean>-->

        <!--redisCacheManager-->
        <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"
              c:redisOperations-ref="redisTemplate"
              p:usePrefix="true" p:transactionAware="true" p:defaultExpiration="${redis.expiration}"><!--启用前缀和事务支持、失效时间-->
              <!--通过设置缓存数据的有效时长可以保证缓存数据的可靠性以及减少内存的占用-->
        </bean>

        <!-- dummy cacheManager  --><!-- 对缓存管理器的统一管理  -->
        <bean id="cacheManager"
              class="org.springframework.cache.support.CompositeCacheManager">
            <property name="cacheManagers">
                <list>
                    <ref bean="redisCacheManager" />
                </list>
            </property>

            <!--在没有cache容器的情况下使用缓存机制,系统会抛出异常,
            所以在不想使用缓存机制时,可以设置fallbackToNoOpCache为true来禁用缓存-->
            <property name="fallbackToNoOpCache" value="false" /><!--设为true则不使用缓存-->
        </bean>

4、使用注解(建议在Service层使用)

public class UserService {

        /**
         * @Cacheable:主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
         * #:SpEL表达式
         * 至少指定一个缓存的名称(value),多个:(value={"cache1","cache2"})
         * 若缓存的key为空则缺省按照方法的所有参数进行组合,多个key组合:key="#userName.concat(#password)"
         * condition:缓存条件,可为空  condition="#userName.length()>4"
         */
        @Cacheable(value = "user",key = "#id")
        public User findUserById(Integer id) {
            log.info("findUserFromDB================================================================");
            return userDao.findUserById(id);
        }


        //@CachePut:每次都执行方法体并对返回结果进行缓存操作
        @CachePut(value = "userLoginIdentity",key = "#user.getId()",condition="#user.getUserName().length()>4")
        public UserLoginIdentity buildUserLoginIdentity(User user){
            UserLoginIdentity userLoginIdentity = new UserLoginIdentity();
            userLoginIdentity.setUserIdString(UserIDBase64.encoderUserID(user.getId()));
            userLoginIdentity.setUserName(user.getUserName());
            userLoginIdentity.setRealName(user.getTrueName());
            return userLoginIdentity;
        }


        /**
         * @CacheEvict:清除缓存
         * allEntries:是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存
         * beforeInvocation:是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,
         *                  缺省情况下,如果方法执行抛出异常,则不会清空缓存
         */
        @CacheEvict(value = {"user","userLoginIdentity"},allEntries = true,beforeInvocation = true)
        public UserLoginIdentity login(String userName, String password) {
            //非空验证
            AssertUtil.isNotEmpty(userName, "用户名不能为空!");
            AssertUtil.isNotEmpty(password, "密码不能为空!");

            User user=userDao.findUserByUserName(userName.trim());
            AssertUtil.notNull(user);

            if (!MD5Util.md5Method(password).equals(user.getPassword())) {
                throw new ParamException(103,"用户密码错误!请重新输入!");
            }
            return buildUserLoginIdentity(user);
        }
    }

关于序列化:keySerializer:这个是对key的默认序列化器

默认值是StringSerializer。
valueSerializer:这个是对value的默认序列化器,
默认值是取自DefaultSerializer的JdkSerializationRedisSerializer。
hashKeySerializer:对hash结构数据的hashkey序列化器,
默认值是取自DefaultSerializer的JdkSerializationRedisSerializer。
hashValueSerializer:对hash结构数据的hashvalue序列化器,
默认值是取自DefaultSerializer的JdkSerializationRedisSerializer。

        从执行时间上来看,JdkSerializationRedisSerializer是最高效的(毕竟是JDK原生的),但是序列化的结果字符串是最长的。
        JSON由于其数据格式的紧凑性,序列化的长度是最小的,时间比前者要多一些。
        而OxmSerialiabler在时间上看是最长的(当时和使用具体的Marshaller有关)。
        所以个人的选择是倾向使用JacksonJsonRedisSerializer作为POJO的序列器。 
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值