使用 Spring 缓存注解时向缓存键添加常量自定义前缀 [英] Add a Constant Custom Prefix to Cache key when using Spring Caching Annotations

查看:26
本文介绍了使用 Spring 缓存注解时向缓存键添加常量自定义前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的服务中使用基于注解的 Spring Cache 抽象.

I am using Spring Cache abstraction based on annotations in my service.

我想在添加到缓存时为键添加自定义前缀.

I want to add a custom prefix to the key when added to the cache.

我创建了一个常量并尝试将它们添加到方法中,如下所示.

I created a constant and tried to add them to the methods as below.

private static final String CACHE_KEY_PREFIX="user";

    @Cacheable(value = "users", key = "{ CACHE_KEY_PREFIX,#userId }")
    @GetMapping("/{userId}")
    public User getUser(@PathVariable String userId) {
        LOG.info("Getting user with ID {}.", userId);
        return userRepository.findOne(Long.valueOf(userId));
    }


    @CacheEvict(value = "users",key="{ CACHE_KEY_PREFIX,#userId }" )
    @DeleteMapping
    public void deleteUserByID(@PathVariable Long userId) {
        LOG.info("deleting person with id {}", userId);
        userRepository.delete(userId);
    }   

但是,我得到如下的堆栈跟踪.

But, I get the stacktrace as below.

2018-06-12 13:35:48.911 ERROR 8728 ---  [nio-8090-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]     Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.expression.spel.SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'hash(#)'] with root cause

org.springframework.expression.spel.SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'hash(#)'
    at org.springframework.expression.spel.standard.InternalSpelExpressionParser.doParseExpression(InternalSpelExpressionParser.java:129)
    at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:60)

由于我有多个方法,我不想在每个方法注释中硬编码自定义前缀.

Since I have multiple methods I do not want to hardcode the custom prefix in every method annotation.

有没有办法添加自定义前缀并避免我看到的异常.

Is there a way to add a custom prefix and avoid the exception I am seeing.

推荐答案

要在注解中使用常量,您可以将其包含为固定字符串,如下所示:

To use a constant in the annotation, you could include it as a fixed String like this:

@Cacheable(value = "users", key = "{'" + CACHE_KEY_PREFIX + "', #userId}")
@GetMapping("/{userId}")
public User getUser(@PathVariable String userId) {
    LOG.info("Getting user with ID {}.", userId);
    return userRepository.findOne(Long.valueOf(userId));
}

在这种情况下,编译器会将属性 key 的值解析为 {'user', #userId}.

In this case, the compiler will resolve the value of attribute key to {'user', #userId}.

这篇关于使用 Spring 缓存注解时向缓存键添加常量自定义前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆