redisCacheManager

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缓存配置文件)

master.name=mymaster
master.password=123456
sentinel.host=127.0.0.1
sentinel1.port=26379
sentinel2.port=26380

#缓存数据库选择
redis.default.db=3
pool.timeout=100000
pool.maxTotal=100
pool.maxActive=100
pool.maxIdle=10
pool.maxWaitMillis=1000

#是否在borrow一个jedis之前就validate
pool.testOnBorrow=true

#缓存数据的最大生命周期,单位:s,-1永久
redis.expiration=-1

#是否禁用缓存,true禁用
cacheManagers.fallbackToNoOpCache=false

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

    <!-- 扫描package方便注解依赖注入-->
    <context:component-scan base-package="com.shop" />

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

    <mvc:annotation-driven/>

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

    <!--哨兵配置-->
    <bean id="redisSentinelConfiguration"
          class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
        <property name="master">
            <bean class="org.springframework.data.redis.connection.RedisNode"
            p:name="${master.name}"/><!--要跟哨兵配置文件监控主机名称一致-->
        </property>
        <property name="sentinels">
            <set>
                <bean class="org.springframework.data.redis.connection.RedisNode"
                    c:host="${sentinel.host}"
                    c:port="${sentinel1.port}"/>
                <bean class="org.springframework.data.redis.connection.RedisNode"
                      c:host="${sentinel.host}"
                      c:port="${sentinel2.port}"/>
            </set>
        </property>
    </bean>

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

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

    <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  -->
    <!--在没有cache容器的情况下使用缓存机制,系统会抛出异常,
        所以在不想使用缓存机制时,可以设置fallbackToNoOpCache为true来禁用缓存-->
    <bean id="cacheManager"
          class="org.springframework.cache.support.CompositeCacheManager"
          p:cacheManagers-ref="redisCacheManager"
          p:fallbackToNoOpCache="${cacheManagers.fallbackToNoOpCache}"/>
        <!--<property name="cacheManagers">
            <list>
                <ref bean="redisCacheManager" />
            </list>
        </property>-->

 

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的序列器。 

转载于:https://my.oschina.net/u/3553440/blog/1543898

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值