找不到Cachable(在EhCache中)

时间:2018-03-13 09:42:37

标签: spring caching ehcache

我有以下结构:

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;

但不知怎的,Cache永远不会被击中。得出结论是因为我可以使用相同的角色调用getRoleCached,但尽管如此,sysout会打印新行。

我的问:如何正确指定key以获得所需的结果?

UPDATE:在提示之后我发现通过Spring代理调用public方法,而直接调用内部(类)。当直接调用时,没有任何进一步的拦截来自Spring完成==&gt;不会检查Cache,即不会应用"L_01"。重构和移动所请求的方法修复了我的概率。

1 个答案:

答案 0 :(得分:1)

@cacheable是使用spring aop代理,因此你不能在私有方法上使用@Cacheable。尝试公共方法