【问题标题】:How to create multiple CacheErrorHandler for multiple CacheManager?如何为多个CacheManager创建多个CacheErrorHandler?
【发布时间】:2018-10-03 09:40:31
【问题描述】:

我正在开发一个 SpringBoot 微服务,它被配置为使用 2 个缓存管理器,EhCache 和 RedisCache,我正在尝试实现 CacheErrorHandler 来分别处理缓存错误。

根据reference,似乎我只能定义一个处理所有类型缓存的CacheErrorHandler。

请问有没有办法为不同的缓存管理器实现不同的CacheErrorHandler?

Redis 缓存管理器 Bean 配置:

@Bean
@Primary
@ConditionalOnBean(CustomCacheProperties.class)
public CacheManager redisCacheManager(RedisConnectionFactory connectionFactory, CustomCacheProperties customCacheProperties) {
    return RedisCacheManager.builder(connectionFactory)
            .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig())
            .withInitialCacheConfigurations(customCacheProperties.getInitialCacheConfigurations())
            .build();
}

EhCache 缓存管理器 Bean 配置:

@Bean(name = "ehcache")
public CacheManager ehcacheManager() {
    return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}

参考:https://dzone.com/articles/safeguard-spring-app-from-cache-failure

【问题讨论】:

    标签: spring spring-boot redis ehcache


    【解决方案1】:

    这是一个老问题,但是当我用谷歌搜索同样的问题时,它就出现了,所以我想我还是会给出答案。

    据我所知,没有办法注册多个错误处理程序,但您可以根据缓存的类型区分错误处理,如下所示:

    @Override
    public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
        if (cache instanceof Ehcache) {
            // ... handle EhCache failure
        } else if (cache instanceof RedisCache) {
            // ... handle Redis failure
        } else {
            // ... fallback
        }
    }
    

    您需要检查您使用的缓存管理器,了解它们创建的缓存的实际类型。

    您还可以创建适当的 bean 实现 CacheErrorHandler,将它们注入到使用 Spring 注册的错误处理程序中,然后从那里进行委托,以正确分离逻辑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多