CacheEventListener 不起作用 Ehcache

问题描述 投票:0回答:2

我正在尝试记录来自 ehcache 的事件,在日志中我看到了缓存、缓存管理器的创建,但没有看到自定义事件侦听器:

2022-09-05 14:49:42.218  INFO 29767 --- [  restartedMain] org.ehcache.jsr107.Eh107CacheManager     : Registering Ehcache MBean javax.cache:type=CacheStatistics,CacheManager=urn.X-ehcache.jsr107-default-config,Cache=primaryUserPhotoResponseCache

缓存事件监听器实现

@Slf4j
@Component
public class EhCacheListener implements CacheEventListener<String, DownloadPrimaryUserPhotoResponse> {
    @Override
    public void onEvent(CacheEvent<? extends String, ? extends DownloadPrimaryUserPhotoResponse> cacheEvent) {
        final var photoURL = cacheEvent.getNewValue().getPhotoURL();

        switch (cacheEvent.getType()) {
            case CREATED -> log.debug("{} been saved to cache",
                    photoURL);
            case REMOVED -> log.debug("{} been removed from cache",
                    photoURL);
            case EXPIRED -> log.debug("{} been has expired",
                    photoURL);
        }
    }
}

ehcache配置

@Configuration
@RequiredArgsConstructor
public class EhCacheConfig {
    public static final String CACHE = "primaryUserPhotoResponseCache";
    private final EhCacheListener listener;

    @Bean
    public CacheManager cacheManager() {
        final var cacheManager = getCachingProvider().getCacheManager();

        javax.cache.configuration.Configuration<String, DownloadPrimaryUserPhotoResponse> config =
                fromEhcacheCacheConfiguration(getCacheConfig());

        cacheManager.createCache(CACHE, config);

        return cacheManager;
    }

    private CacheConfiguration<String, DownloadPrimaryUserPhotoResponse> getCacheConfig() {
        final var pool = newResourcePoolsBuilder()
                .offheap(20, MB)
                .build();

        return newCacheConfigurationBuilder(
                String.class, DownloadPrimaryUserPhotoResponse.class, pool)
                .withExpiry(timeToIdleExpiration(Duration.ofHours(1))) 
                .withService(getCacheEventListenerBuilder())
                .build();
    }

    private CacheEventListenerConfigurationBuilder getCacheEventListenerBuilder() {
        return newEventListenerConfiguration(listener, CREATED, EXPIRED, REMOVED)
                .asynchronous()
                .unordered();
    }
}

运行项目时我没有遇到任何错误,侦听器只是无法工作

spring spring-boot ehcache
2个回答
0
投票

您需要更改 offheaph(10, MB) 并删除 1 个 CASE


0
投票

需要加上这个

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.cache</groupId>
            <artifactId>cache-api</artifactId>
            <version>1.1.1</version>
        </dependency>
© www.soinside.com 2019 - 2024. All rights reserved.