美文网首页
spring cache+redis缓存使用

spring cache+redis缓存使用

作者: 多关心老人 | 来源:发表于2018-01-11 00:27 被阅读0次

工作中缓存代码和业务代码混淆在一起,这种代码侵入性太强,而且很容易混乱,忘记写缓存等等,如下代码。

public Object get(String key){
     String ret = this.jedis.get(key);
     if(ret == null){
          ret = DAO.getFromDB(key);
          this.jedis.set(key, ret);  
    }else{
          return ret;
    }

另一种写法相对优雅一些,参考HibernateTemplate/RedisTemplate:

 T CacheTemplate.get(String key, int seconds, DbCallback<T> callback)

这种写法通过回调,在缓存中没有数据的时候才去db中查找。

还有一种方法我认为最优雅,就是在方法上加注解,这样基本做到对业务代码0侵入,和业务代码分离,对程序员非常友好,注解相比xml零散但灵活度高。sprig cache提供了@Cacheable和@CacheEvit、@CachePut等注解,xml中配置<cache:annotation-driven>,在想要缓存或清缓存的方法上加相应注解即可spring cache提供的注解需要制定在哪个Cache上操作及Key值,key支持SpEL。不过spring cache注解不支持设置失效时间,这里自己实现一个@CacheExpire注解设置失效时间,在切面中读取注解把失效时间保存到ThreadLocal中,处理@CacheExpire的切面要在@Caccheable切面的前面,不然在保存缓存的时候还没拿到失效时间值。

<!--为了避免jdk aop类内方法直接调用不走切面,这里固定使用cglib,或者设置mode="aspectj"都可以-->
    <cache:annotation-driven proxy-target-class="true" order="10"/>
    <!-- 切面逻辑 -->
    <bean id="redisCacheAdvice" class="com.cache.config.CacheExpireAdvice"/>
    <aop:config proxy-target-class="true">
        <aop:pointcut id="cacheExpire" expression="execution(* com.cache.service.*.*(..)) and @annotation(com.cache.config.CacheExpire)"/>
        <!-- 只有一个切入点和切入逻辑,用aop:advisor就好,如果有多个pointcut和advice,请用aop:aspect -->
        <!-- 解析@CacheExpire的切面要在CacheInterceptor前面-->
        <aop:advisor order="9" advice-ref="redisCacheAdvice" pointcut-ref="cacheExpire"/>
    </aop:config>

spring cache默认提供的RedisCache不会用,自己实现MyRedisCache,在MyRedisCache调用jedis保存缓存,这里能拿到缓存失效时间值。

@Override
    public <T> T get(Object key, Class<T> type) {
        Objects.requireNonNull(key);
        byte[] bytes = this.shardedJedis.get(key.toString().getBytes());
        if(bytes != null && bytes.length > 0){
            return null;
        }
        Object object = RedisByteSerializer.toObject(bytes);
        if(type.isAssignableFrom(object.getClass())){
            return (T)object;
        }else{
            return null;
        }
    }

@Override
    public void put(Object key, Object value) {
        Objects.requireNonNull(key);
        if(ThreadLocalUtils.getCacheExpireHolder().get()!=null && ThreadLocalUtils.getCacheExpireHolder().get() > 0){
            this.logger.info("cache with expire.....");
            this.shardedJedis.setex(key.toString().getBytes(), ThreadLocalUtils.getCacheExpireHolder().get(), RedisByteSerializer.toByteArray(value));
        }else{
            this.logger.info("cache without expire.....");
            this.shardedJedis.set(key.toString().getBytes(), RedisByteSerializer.toByteArray(value));
        }
    }

在这里javabean要实现Serializable,要定义serialVersionUID=-1,key/value直接用byte[]存储,key用String.getBytes(),类似于StringRedisSerializer,value用Jdk的序列和反序列化,类似于JdkSerializationRedisSerializer。这里不能用jackson2,因为jackson2需要Class type,这里给不了。

ShardedJedis用了FactoryBean+jdk proxy实现,实现了JedisCommands和BinaryJedisCommands接口。

public class ShardedJedis implements FactoryBean<JedisCommand>, InvocationHandler {

    @Autowired
    private ShardedJedisPool shardedJedisPool;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        //这里最好用try finally,可以监控redis性能,发送到统计中心。这里主要是用try resource尝鲜
        try (redis.clients.jedis.ShardedJedis shardedJedis = this.shardedJedisPool.getResource()) {
            return method.invoke(shardedJedis, args);
        }
    }

    @Override
    public JedisCommand getObject() throws Exception {
        return (JedisCommand) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{JedisCommand.class}, this);
    }
}

try-resource是语法糖,在try{}块执行完毕后jvm会自动释放在try()中定义的资源。
这里这样写的目的一是偷懒,不想实现JedisCommands和BinaryJedisCommands中上百个方法;二是统一释放从ShardJedisPool借来的资源,防止程序员忘还资源。

使用的时候直接在方法上面加注解即可。

@Service
public class AccountService {

    private final Logger logger = LoggerFactory.getLogger(AccountService.class);

    @Cacheable(value = "redis", key = "'test:'.concat(#accountName)")
    @CacheExpire(20)
    @DataSource(DataSourceEnum.READ)
    public Account getAccountByName(String accountName) {
        Optional<Account> accountOptional = getFromDB(accountName);
        if (!accountOptional.isPresent()) {
            throw new IllegalStateException(String.format("can not find account by account name : [%s]", accountName));
        }
        return accountOptional.get();
    }

    @CacheEvict(value = "redis", key = "'test:'.concat(#accountName)")
    @DataSource
    public int update(String accountName){//update db, evict cache
        this.logger.info("update or delete account from DB, evict from cache");
        return 1;
    }

    private Optional<Account> getFromDB(String accountName) {
        logger.info("=====================real querying db... {}", accountName);
        return Optional.of(new Account(accountName));
        //throw new UnsupportedOperationException();//抛异常,事务执行失败,外层的Cache也会失败
    }
}

代码见:https://github.com/HiwayChe/zheng/tree/develop/zheng-test
执行日志分析见https://www.jianshu.com/p/e9fdb735bdb8

相关文章

网友评论

      本文标题:spring cache+redis缓存使用

      本文链接:https://www.haomeiwen.com/subject/qpuinxtx.html