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

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

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

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

import java.lang.reflect.Method;
import java.util.Optional;

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

    public RedisCacheEvictAfterAdvice(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);
        RedisCacheEvict cacheEvict = method.getAnnotation(RedisCacheEvict.class);
        String cacheName = StringUtils.hasLength(cacheEvict.cacheName())
                ? cacheEvict.cacheName()
                : CacheUtils.generateName(target);
        String key = cacheEvict.key();

        if (StringUtils.hasLength(key)) {
            key = SpELContext.parserEl(key);
            this.remove(cacheName + ":" + key);
        } else {
            Optional.ofNullable(redisTemplate.keys(cacheName.concat("*")))
                    .ifPresent(keys -> keys.stream()
                            .filter(k -> k.startsWith(cacheName))
                            .forEach(this::remove));
        }

        SpELContext.removeContext();
    }

    private void remove(String key) {
        log.trace("Cache >>> delete key >>> {}", key);
        redisTemplate.delete(key);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy