简体   繁体   English

如何使用 Spring 清除所有 Hibernate 缓存(ehcache)?

[英]How to clear all Hibernate cache (ehcache) using Spring?

I am using 2nd level cache and query cache.我正在使用二级缓存和查询缓存。 May I know how to programmatically clear all caches ?我可以知道如何以编程方式清除所有缓存吗?

The code snippet indicated in Bozho answer is deprecated in Hibernate 4. Bozho 回答中指示的代码片段在 Hibernate 4 中已弃用。

According to Hibernate JavaDoc, you can use org.hibernate.Cache.evictAllRegions() :根据 Hibernate JavaDoc,您可以使用org.hibernate.Cache.evictAllRegions()

Evict data from all query regions.从所有查询区域中驱逐数据。

Using the API :使用 API :

Session session = sessionFactory.getCurrentSession();

if (session != null) {
    session.clear(); // internal cache clear
}

Cache cache = sessionFactory.getCache();

if (cache != null) {
    cache.evictAllRegions(); // Evict data from all query regions.
}

Alternatively, you can clear all data from a specific scope :或者,您可以清除特定范围内的所有数据:

org.hibernate.Cache.evictCollectionRegions()
org.hibernate.Cache.evictDefaultQueryRegion()
org.hibernate.Cache.evictEntityRegions()
org.hibernate.Cache.evictQueryRegions()
org.hibernate.Cache.evictNaturalIdRegions()

You might want to check the JavaDoc for hibernate Cache interface (Hibernate 4.3) .您可能需要查看JavaDoc 以获取 hibernate Cache interface (Hibernate 4.3)

And also, second-level cache eviction from hibernate dev guide (4.3).此外,从休眠开发指南 (4.3) 中驱逐二级缓存

To clear the session cache use session.clear()要清除会话缓存使用session.clear()

To clear the 2nd level cache use this code snippet要清除二级缓存,请使用此代码片段

If you plug in Terracotta, you also have the ability to run the Terracotta Dev Console which can inspect statistics about the cache, turn on and turn off the cache, and clear the cache contents from the user interface.如果您插入 Terracotta,您还可以运行 Terracotta Dev Console,它可以检查有关缓存的统计信息、打开和关闭缓存以及从用户界面清除缓存内容。

This functionality is also available from JMX beans. JMX bean 也提供此功能。

@Dino 's answer almost worked for me but I got an error from sessionFactory.getCurrentSession() (No currentSessionContext configured!). @Dino 的回答几乎对我有用,但我从sessionFactory.getCurrentSession()得到一个错误(没有配置 currentSessionContext!)。 I found this worked for me:我发现这对我有用:

    // Use @Autowired EntityManager em
    em.getEntityManagerFactory().getCache().evictAll();

    // All of the following require org.hibernate imports
    Session session = em.unwrap(Session.class);

    if (session != null) {
        session.clear(); // internal cache clear
    }

    SessionFactory sessionFactory = em.getEntityManagerFactory().unwrap(SessionFactory.class);

    Cache cache = sessionFactory.getCache();

    if (cache != null) {
        cache.evictAllRegions(); // Evict data from all query regions.
    }

Same as @Dino's answer, shortened syntax for JPA 2.0 API:与@Dino 的回答相同,缩短了 JPA 2.0 API 的语法:

@Autowired
private EntityManagerFactory entityManagerFactory;

public void clearHibernateCaches() {
    entityManagerFactory.getCache().unwrap(org.hibernate.Cache.class).evictAllRegions();
}

If you want to clear 2nd level cache, use api sessionFactory.evictEntity(entityName)如果要清除二级缓存,请使用 api sessionFactory.evictEntity(entityName)

Code:代码:

/**
 * Evicts all second level cache hibernate entites. This is generally only
 * needed when an external application modifies the database.
 */
public void evict2ndLevelCache() {
    try {
        Map<String, ClassMetadata> classesMetadata = sessionFactory.getAllClassMetadata();
        for (String entityName : classesMetadata.keySet()) {
            logger.info("Evicting Entity from 2nd level cache: " + entityName);
            sessionFactory.evictEntity(entityName);
        }
    } catch (Exception e) {
        logger.logp(Level.SEVERE, "SessionController", "evict2ndLevelCache", "Error evicting 2nd level hibernate cache entities: ", e);
    }
}

For more details on 2nd level cache refer有关二级缓存的更多详细信息, 请参阅

you can go with this also你也可以用这个

request.getSession().invalidate();      
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); 
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM