简体   繁体   English

Java SE应用程序中的休眠并发问题

[英]Hibernate Concurrency issue in Java SE application

I am building a Java SE application that is powered by Hibernate. 我正在构建一个由Hibernate支持的Java SE应用程序。 Mainly many Java SE instances would run and there would be many Hibernate Session factories. 主要将运行许多Java SE实例,并且将有许多Hibernate Session工厂。 When one client machine insert an Object to the datasource, other clients won't see it unless I clear the cache. 当一台客户端计算机将对象插入数据源时,其他客户端将不会看到它,除非我清除了缓存。 Is there a better mechanism to use in this case? 在这种情况下是否有更好的机制可以使用? Below is my cache clearing method. 下面是我的缓存清除方法。

public static void clearCache() {
        HibernateHelper.beginTranscation();
        HibernateHelper.getCurrentSession().clear();
        HibernateHelper.getSessionFactory().evictQueries();
        try {
            Map<String, ClassMetadata> classesMetadata = HibernateHelper
                    .getSessionFactory().getAllClassMetadata();
            for (String entityName : classesMetadata.keySet()) {
                HibernateHelper.getSessionFactory().evictEntity(entityName);
            }
        } catch (Exception e) {
        }
        HibernateHelper.commit();
    }

Please note the fact that I am using the Second Level cache (Memcache) and Query cache as well. 请注意,我也在使用二级缓存(Memcache)和查询缓存。

The way you are using the L2 cache might cause data inconsistency as your application is using multiple session factories and hence it's distributed and needs distributed cache . 您的应用程序使用多个会话工厂时,使用L2缓存的方式可能会导致数据不一致,因此它是分布式的因此需要分布式缓存

Here is how your system looks 这是您的系统外观

在此处输入图片说明

OR 要么

Alternatively you can have a central memcache server which each of the client (with the help of memcached client ) will use. 或者,您可以有一个中央的Memcache服务器,每个客户端(在memcached client的帮助下)都将使用该服务器。 (One memcached used by all users ) (所有用户使用一个memcached)

The basic requirement is that the changes committed by one user/session factory should be visible to the other users/session factory for leveraging the cache. 基本要求是, 一个用户/会话工厂提交更改对于其他用户/会话工厂应该是可见的,以便利用缓存。 The code sample given by you is not helpful as it will clean the L2 cache every time a transaction commits. 您提供的代码示例没有帮助,因为它将在每次提交事务时清除L2缓存。 This is anyways done by L2 cache or session cache . 无论如何,这是由L2缓存或会话缓存完成的

so my suggestions would be 所以我的建议是

  1. Don't use L2 cache at all hence no local memcache. 根本不使用L2缓存,因此没有本地内存缓存。 You are not leveraging it anyways as you are cleaning the cache after every transaction. 您不会在任何事务中都利用它,因为在每次事务处理后都要清理缓存。
  2. If at all L2 cache is needed, use a distributed cache (which is slightly complicated) OR use a single memcached server for all. 如果完全需要二级缓存,则使用分布式缓存(这有点复杂),或者全部使用一个内存缓存服务器。

Please check this link as well. 请同时检查此链接

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

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