All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.feingto.cloud.config.redis.adapter.RedisCachePutAfterAdvice Maven / Gradle / Ivy

The newest version!
package com.feingto.cloud.config.redis.adapter;

import com.feingto.cloud.config.redis.RedisCachePut;
import com.feingto.cloud.config.redis.support.CacheUtils;
import com.feingto.cloud.config.redis.support.SpELContext;
import com.feingto.cloud.kit.json.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

/**
 * RedisCachePut 后置通知代理
 *
 * @author longfei
 */
@Slf4j
public class RedisCachePutAfterAdvice implements AfterReturningAdvice {
    private final RedisTemplate redisTemplate;

    public RedisCachePutAfterAdvice(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        SpELContext.putContext(this.getClass(), method, args);
        RedisCachePut cachePut = method.getAnnotation(RedisCachePut.class);
        String cacheName = StringUtils.hasLength(cachePut.cacheName())
                ? cachePut.cacheName()
                : CacheUtils.generateName(target);
        String key = StringUtils.hasLength(cachePut.key())
                ? SpELContext.parserEl(cachePut.key())
                : CacheUtils.generateKey(method, args);

        BoundValueOperations opts = redisTemplate.boundValueOps(cacheName + ":" + key);
        log.trace("Cache >>> put key >>> {}", key);
        opts.set(JSON.obj2json(returnValue));

        long expire = cachePut.expire();
        if (expire > 0) {
            opts.expire(expire, cachePut.timeUnit());
        }

        SpELContext.removeContext();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy