【发布时间】:2018-08-21 12:15:34
【问题描述】:
我有以下构造:
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 会打印新行。
我的问题:如何正确指定key以获得想要的结果?
更新:提示后我发现public 方法是通过 Spring 代理调用的,而内部(类的)是直接调用的。当直接调用时,Spring done ==> 不会检查 Cache 的任何进一步拦截,即不应用。重构和移动请求的方法解决了我的问题。
【问题讨论】: