我有以下结构:
public List<Integer> getCurrentRoleDetails(){
return getRoleCached(getCurrentRole());
}
@Cacheable(value = "roleWrite", key = "#role.getRoleId()")
private final List<Integer> getRoleCached(final Role role) {
System.out.println("role...= " + role.getRoleId());
和配置
@EnableCaching
@Configuration
public class CacheConf {
// EhCache based CacheManager, most commonly used in Enterprise
// applications.
@Bean
public CacheManager cacheManager() {
final EhcacheCachingProvider provider = (EhcacheCachingProvider) Caching.getCachingProvider();
final Map<String, CacheConfiguration<?, ?>> caches = new HashMap<>();
caches.put("roleWrite", getCache());
final DefaultConfiguration configuration = new DefaultConfiguration(caches, provider.getDefaultClassLoader());
return new JCacheCacheManager(provider.getCacheManager(provider.getDefaultURI(), configuration));
}
private CacheConfiguration<?, ?> getCache() {
final ResourcePoolsBuilder res = ResourcePoolsBuilder.heap(100);
// Spring does not allow anything else than Objects...
final CacheConfigurationBuilder<Object, Object> newCacheConfigurationBuilder = CacheConfigurationBuilder
.newCacheConfigurationBuilder(Object.class, Object.class, res);
return newCacheConfigurationBuilder.build();
}
与实体:
@Data // lombok generates the Getter and Setters
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer roleId;
但不知何故,缓存从未被击中。结论之所以出现,是因为我可以使用相同的角色调用getRoleCached
,但尽管如此,sysout
打印新行。
我的q:如何正确指定key
以获得所需的结果?
更新:在提示之后,我发现public
方法是通过 Spring 代理调用的,而内部(类的(是直接调用的。当直接调用时,Spring 不会有任何进一步的拦截 完成 ==> 不会检查Cache
,即不应用。重构和移动请求的方法修复了我的问题。
@Cacheable使用Spring AOP代理,因此您不能在私有方法上使用@Cacheable。 尝试公共方法