绕过生产中的@Cacheable注释进行调试

时间:2011-05-22 10:11:57

标签: java spring caching

我正在开发一个基于Spring的新项目,我想知道,如果我要使用Spring 3.1或ehcache-spring-annotation项目中的@Cacheable注释,你将如何实现一个机制?例如,“按需”绕过缓存机制用于生产调试。

假设我的应用程序仅提供REST请求,有时,我想,一次调用(我手动制作)直接从“数据库”(或者有后端)获取数据并避免和任何在途中缓存(任何缓存)。当调用正在运行时,我真的不介意它是否重新填充缓存与它从db中获得的内容...

我想听听你对如何实现这一点的想法。

提前感谢任何指导,

3 个答案:

答案 0 :(得分:0)

除了现有的检查之外,您可以扩展缓存管理器并提供布尔表达式。

您可以在控制器的ThreadLocal中设置该布尔值,这样无论何时调用服务,布尔值就会到位。

答案 1 :(得分:0)

如果需要数据库中的值,可以创建一个刷新缓存并仅使用调试器运行缓存的方法。

@Cacheable(modelId = "i18NTextCacheModel")
public List<I18NText> loadAll() {

    logger.debug("loadAll called");
    ...
}

@CacheFlush(modelId = "i18NTextFlushModel")
public Long save(I18NText entity) {

    logger.debug("save called");
    ...
}

答案 2 :(得分:0)

与@Bozho建议的结果相似 如果传递了请求参数 refresh-cache = true ,则缓存将被绕过

我扩展了DefaultRedisCacheWriter并将其用作CacheWriter

    RedisCacheManager cacheManager = RedisCacheManager
            .builder(new RefreshableRedisCacheWriter(redisConnectionFactory()))
            .cacheDefaults(cacheConfiguration)
            .build();

覆盖此编写器中的get()方法

@Override
public byte[] get(String name, byte[] key) {

    Assert.notNull(name, "Name must not be null!");
    Assert.notNull(key, "Key must not be null!");

    HttpServletRequest request = ApiRequestContext.getRequestContext();
    if (Boolean.valueOf(request.getParameter("refresh-cache"))) {
        logger.info("bypassing cache for key: {}", key);
        return null;
    }

    return execute(name, connection -> connection.get(key));
}

ApiRequestContext是一个自定义请求对象,此处存储在线程本地中。 请注意,当此方法返回null时,将从数据库中获取值并将其放回缓存中,从而有效地刷新缓存。