【问题标题】:Cachable not found (in EhCache)未找到可缓存(在 EhCache 中)
【发布时间】: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 的任何进一步拦截,即不应用。重构和移动请求的方法解决了我的问题。

【问题讨论】:

    标签: spring caching ehcache


    【解决方案1】:

    @Cacheable 是使用 spring aop 代理,所以你不能在私有方法上使用 @Cacheable。试试公共方法

    【讨论】:

    • public 没有帮助 - 删除 final
    • 我编写了一个与您的代码相同的示例。它运作良好。 github.com/luolibing/coding-life/tree/master/modules/ehcache
    • 在对代码进行测试和进一步调查之后,我发现了真正的问题是什么。我想这是与您的代码类似的问题:invokePrivate() 没有参数role - 但是您设置了密钥 - 这是不合逻辑的。我有另一个问题 - 更新了我的 q.无论如何,我现在对机制有了更好的了解。谢谢!
    猜你喜欢
    • 2022-08-21
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    相关资源
    最近更新 更多