我有一个没有参数的方法,我想缓存返回值。作为缓存密钥,我想从安全上下文中使用当前经过身份验证的用户
@Cacheable(value = "resultCache", key="#userPrincipal.id") public result getResult() {}
@Cacheable(value = "resultCache", key="#userPrincipal.id")
public result getResult() {}
是可能的还是我的想法错了。
bksxznpy1#
您有四个选项来实现这一点:发送 Authentication 对象作为方法参数:
Authentication
@Cacheable(value = "resultCache", key="#authentication.name")public Result getResult(Authentication authentication) {}
@Cacheable(value = "resultCache", key="#authentication.name")
public Result getResult(Authentication authentication) {}
创建自定义 KeyGenerator 在你的生活中使用它 @Cacheable 注解
KeyGenerator
@Cacheable
public class CustomKeyGenerator implements KeyGenerator { @Override public Object generate(Object target, Method method, Object... params) { return SecurityContextHolder.getContext().getAuthentication().getName(); }}@Configuration@EnableCachingpublic class CacheConfiguration { @Bean("customKeyGenerator") public KeyGenerator customKeyGenerator() { return new CustomKeyGenerator(); }}@Cacheable(value = "resultCache", keyGenerator="customKeyGenerator")public Result getResult() {}
public class CustomKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object target, Method method, Object... params) {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
@Configuration
@EnableCaching
public class CacheConfiguration {
@Bean("customKeyGenerator")
public KeyGenerator customKeyGenerator() {
return new CustomKeyGenerator();
@Cacheable(value = "resultCache", keyGenerator="customKeyGenerator")
public Result getResult() {}
创建一个bean,为您提供密钥并通过 key 财产。我建议您采用这种方法,因为它允许您稍后更轻松地更改值。
key
@Componentpublic class CacheKeyProvider { public String getUsernameKey() { return SecurityContextHolder.getContext().getAuthentication().getName(); }}@Cacheable(value = "resultCache", key="@cacheKeyProvider.getUsernameKey()")public Result getResult() {}
@Component
public class CacheKeyProvider {
public String getUsernameKey() {
@Cacheable(value = "resultCache", key="@cacheKeyProvider.getUsernameKey()")
使用类型spel表达式
@Cacheable(value = "resultCache", key="T(org.springframework.security.core.context.SecurityContextHolder.getContext()?.authentication?.name)")public Result getResult() {}
@Cacheable(value = "resultCache", key="T(org.springframework.security.core.context.SecurityContextHolder.getContext()?.authentication?.name)")
注意,我使用了 name 来自 Principal 在例子中。但是如果你有一个习惯 Principal 对象,您可以强制转换它并返回所需的任何属性。
name
Principal
1条答案
按热度按时间bksxznpy1#
您有四个选项来实现这一点:
发送
Authentication
对象作为方法参数:创建自定义
KeyGenerator
在你的生活中使用它@Cacheable
注解创建一个bean,为您提供密钥并通过
key
财产。我建议您采用这种方法,因为它允许您稍后更轻松地更改值。使用类型spel表达式
注意,我使用了
name
来自Principal
在例子中。但是如果你有一个习惯Principal
对象,您可以强制转换它并返回所需的任何属性。