Spring 键的可缓存连接参数

Spring Cacheable concat patameters for key

我正在使用 Spring 缓存框架和 redis。以下是我使用的缓存

@Cacheable(value = "oauth2token", key="#value + #type")
public OAuth2Token findOneByValueAndType(String value, String type);

我只是想创建一个我知道的密钥。这给出了错误

14:20:21,199 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/veip-web].[Resteasy]] (http-/0.0.0.0:8080-63) JBWEB000236: Servlet.service() for servlet Resteasy threw exception: org.springframework.expression.spel.SpelEvaluationException: EL1030E:(pos 0): The operator 'ADD' is not supported between objects of type 'null' and 'null'

因为当我没有指定 key as fllows 时。

@Cacheable(value = "oauth2token")
public OAuth2Token findOneByValueAndType(String value, String type);

我可以看到生成了一个疯狂的密钥。我需要知道密钥,因为稍后我需要 CachePut 并更新相同的项目。

我也试过以下。

@Cacheable(value = "oauth2token", key="#type.contact(#value)")
public OAuth2Token findOneByValueAndType(String value, String type);

Spring 抱怨当时 #type 为空。

这里有什么问题。

您可能没有每个参数名称的运行时信息(#value 不知道)。更安全的方法是使用 #p#a 别名,这样 总是 有效。 key="#p0 + #p1" 应该可以解决问题。

话虽如此,我不会那样做。如果您在另一个带注释的方法中重用密钥,我会将 implement KeyGenerator 作为一个 bean,并在需要处理这两个值的方法中传递该 bean 的引用。这样您就可以共享(和测试)该代码并避免重复。