使用Spring SpEL表达式获取注释中引用的动态参数

时间:2018-12-17 20:29:09

标签: java spring spring-boot aop spring-aop

我正在尝试做的是一个Annotation,它看起来很像Spring提供的@Cacheable Annotation。

在方法顶部使用,它看起来如下所示:

@CleverCache(key = "'orders_'.concat(#id)")
public Order getOrder(int id) {

当我通过Cacheable使用它时,它可以某种方式解释此SpEL表达式并生成具有值orders_1234(对于id = 1234)的键

我的匹配建议如下:

@Around("CleverCachePointcut(cleverCache)")
public Object clevercache(ProceedingJoinPoint joinPoint, CleverCache cleverCache) throws Throwable {
    String expression = cleverCache.key();
    //FIXME: Please add working code here :D - extracting the key by interpreting the passed SpEL Expression in expression

我确实在那儿得到了表达式,但是我还没有弄清楚它如何正确解释SpEL表达式。

另一种支持语法应为key = "T(com.example.Utils).createCacheKey(#paramOfMethodByName)",其中将调用用于创建密钥的静态助手。

有人知道这怎么工作吗?我的摘录来自以下位置的代码:https://github.com/eiselems/spring-redis-two-layer-cache/blob/master/src/main/java/com/marcuseisele/example/twolayercache/clevercache/ExampleAspect.java#L35

我们非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

如果您有必要的上下文信息,评估SpEL实际上非常简单。请参阅this article,以了解如何以编程方式解析SpEL。

关于上下文信息,您没有对由@CleverCache注释的方法类型进行过多解释。关键是,切入点会拦截所有带注释的方法,并且我不知道每个人的第一个参数是否为int ID。根据此问题的答案,更容易(仅是一种简单的情况)或更难(您需要if-else才能找到具有整数ID的方法)以从截获的方法中获取ID参数值。或者,也许您有各种各样的表达式,它们引用方法参数,实例变量等的多种类型和名称。解决方案的复杂性与需求的复杂性相关。如果您提供更多信息,也许我也可以提供更多帮助。


更新:查看了您的GitHub存储库后,我为简单的案例重构了您的方面:

package com.marcuseisele.example.twolayercache.clevercache;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
@Slf4j
public class ExampleAspect {
    private static final ExpressionParser expressionParser = new SpelExpressionParser();

    private Map<String, RedisTemplate> templates;

    public ExampleAspect(Map<String, RedisTemplate> redisTemplateMap) {
        this.templates = redisTemplateMap;
    }

    @Pointcut("@annotation(cleverCache)")
    public void CleverCachePointcut(CleverCache cleverCache) {
    }

    @Around("CleverCachePointcut(cleverCache) && args(id)")
    public Object clevercache(ProceedingJoinPoint joinPoint, CleverCache cleverCache, int id) throws Throwable {
        long ttl = cleverCache.ttl();
        long grace = cleverCache.graceTtl();

        String key = cleverCache.key();
        Expression expression = expressionParser.parseExpression(key);
        EvaluationContext context = new StandardEvaluationContext();
        context.setVariable("id", id);
        String cacheKey = (String) expression.getValue(context);
        System.out.println("### Cache key: " + cacheKey);

        long start = System.currentTimeMillis();
        RedisTemplate redisTemplate = templates.get(cleverCache.redisTemplate());
        Object result;
        if (redisTemplate.hasKey(cacheKey)) {
            result = redisTemplate.opsForValue().get(cacheKey);
            log.info("Reading from cache ..." + result.toString());

            if (redisTemplate.getExpire(cacheKey, TimeUnit.MINUTES) < grace) {
                log.info("Entry is in Grace period - trying to refresh it");
                try {
                    result = joinPoint.proceed();
                    redisTemplate.opsForValue().set(cacheKey, result, grace+ttl, TimeUnit.MINUTES);
                    log.info("Fetch was successful - new value will be returned");
                } catch (Exception e) {
                    log.warn("An error occured while trying to refresh the value - extending the old one", e);
                    //TODO: think about only adding 5 minutes on top of grace, or 50% of ttl on top of grace
                    //if protected by a circuit breaker we could go REALLY low here
                    redisTemplate.opsForValue().getOperations().expire(cacheKey, grace+ttl, TimeUnit.MINUTES);
                }

            }

        } else {
            result = joinPoint.proceed();
            log.info("Giving from method ..." + result.toString());
            redisTemplate.opsForValue().set(cacheKey, result, ttl + grace, TimeUnit.MINUTES);
        }

        long executionTime = System.currentTimeMillis() - start;
        log.info("{} executed in {} ms", joinPoint.getSignature(), executionTime);
        log.info("Result: {}", result);
        return result;
    }
}

差异看起来像这样:

Diff screenshot