spring cache+redis緩存使用

工作中緩存代碼和業務代碼混淆在一起,這種代碼侵入性太強,而且很容易混亂,忘記寫緩存等等,如下代碼。

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
執行日志分析見http://www.lxweimin.com/p/e9fdb735bdb8

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。