草庐IT

java - 如何使用 JPA 和 Hibernate 拆分只读和读写事务

coder 2023-05-19 原文

我有一个非常重的 java webapp,它可以处理数千个请求/秒,它使用一个主 Postgresql db,它使用流式(异步)复制将自身复制到一个辅助(只读)数据库。

因此,考虑到复制时间最短,我使用 URL 将请求从主要请求分离到次要(只读)以避免对错误主数据库的只读调用。

注意 :我使用一个 sessionFactory 和一个由 spring 提供的 RoutingDataSource,它根据一个键查找要使用的数据库。我对 Multi-Tenancy 感兴趣,因为我使用的是支持它的 hibernate 4.3.4。

我有两个问题:

  • 我不认为基于 URL 的拆分是有效的
    只移动 10% 的流量意味着没有多少只读
    网址。我应该考虑什么方法?
  • 可能是,不知何故,在 URL 的基础上,我达到了某种程度
    两个节点之间的分布,但我会用我的 quartz 做什么
    工作(甚至有单独的 JVM)?我应该采取什么务实的方法
    拿?

  • 我知道我可能不会在这里得到完美的答案,因为这确实很广泛,但我只是想了解您对上下文的看法。

    我的团队中的伙计们:
  • Spring4
  • Hibernate4
  • Quartz2.2
  • Java7/Tomcat7

  • 请感兴趣。提前致谢。

    最佳答案

    Spring事务路由
    首先,我们将创建一个 DataSourceType定义我们的事务路由选项的 Java 枚举:

    public enum  DataSourceType {
        READ_WRITE,
        READ_ONLY
    }
    
    要将读写事务路由到主节点并将只读事务路由到副本节点,我们可以定义一个 ReadWriteDataSource连接到主节点和 ReadOnlyDataSource连接到副本节点。
    读写和只读事务路由由 Spring AbstractRoutingDataSource 完成抽象,由 TransactionRoutingDatasource 实现,如下图所示:
    TransactionRoutingDataSource很容易实现,如下所示:
    public class TransactionRoutingDataSource 
            extends AbstractRoutingDataSource {
    
        @Nullable
        @Override
        protected Object determineCurrentLookupKey() {
            return TransactionSynchronizationManager
                .isCurrentTransactionReadOnly() ?
                DataSourceType.READ_ONLY :
                DataSourceType.READ_WRITE;
        }
    }
    
    基本上,我们检查 Spring TransactionSynchronizationManager存储当前事务上下文以检查当前运行的 Spring 事务是否为只读的类。determineCurrentLookupKey方法返回将用于选择读写或只读 JDBC DataSource 的鉴别器值.
    Spring读写只读的JDBC DataSource配置DataSource配置如下:
    @Configuration
    @ComponentScan(
        basePackages = "com.vladmihalcea.book.hpjp.util.spring.routing"
    )
    @PropertySource(
        "/META-INF/jdbc-postgresql-replication.properties"
    )
    public class TransactionRoutingConfiguration 
            extends AbstractJPAConfiguration {
    
        @Value("${jdbc.url.primary}")
        private String primaryUrl;
    
        @Value("${jdbc.url.replica}")
        private String replicaUrl;
    
        @Value("${jdbc.username}")
        private String username;
    
        @Value("${jdbc.password}")
        private String password;
    
        @Bean
        public DataSource readWriteDataSource() {
            PGSimpleDataSource dataSource = new PGSimpleDataSource();
            dataSource.setURL(primaryUrl);
            dataSource.setUser(username);
            dataSource.setPassword(password);
            return connectionPoolDataSource(dataSource);
        }
    
        @Bean
        public DataSource readOnlyDataSource() {
            PGSimpleDataSource dataSource = new PGSimpleDataSource();
            dataSource.setURL(replicaUrl);
            dataSource.setUser(username);
            dataSource.setPassword(password);
            return connectionPoolDataSource(dataSource);
        }
    
        @Bean
        public TransactionRoutingDataSource actualDataSource() {
            TransactionRoutingDataSource routingDataSource = 
                new TransactionRoutingDataSource();
    
            Map<Object, Object> dataSourceMap = new HashMap<>();
            dataSourceMap.put(
                DataSourceType.READ_WRITE, 
                readWriteDataSource()
            );
            dataSourceMap.put(
                DataSourceType.READ_ONLY, 
                readOnlyDataSource()
            );
    
            routingDataSource.setTargetDataSources(dataSourceMap);
            return routingDataSource;
        }
    
        @Override
        protected Properties additionalProperties() {
            Properties properties = super.additionalProperties();
            properties.setProperty(
                "hibernate.connection.provider_disables_autocommit",
                Boolean.TRUE.toString()
            );
            return properties;
        }
    
        @Override
        protected String[] packagesToScan() {
            return new String[]{
                "com.vladmihalcea.book.hpjp.hibernate.transaction.forum"
            };
        }
    
        @Override
        protected String databaseType() {
            return Database.POSTGRESQL.name().toLowerCase();
        }
    
        protected HikariConfig hikariConfig(
                DataSource dataSource) {
            HikariConfig hikariConfig = new HikariConfig();
            int cpuCores = Runtime.getRuntime().availableProcessors();
            hikariConfig.setMaximumPoolSize(cpuCores * 4);
            hikariConfig.setDataSource(dataSource);
    
            hikariConfig.setAutoCommit(false);
            return hikariConfig;
        }
    
        protected HikariDataSource connectionPoolDataSource(
                DataSource dataSource) {
            return new HikariDataSource(hikariConfig(dataSource));
        }
    }
    
    /META-INF/jdbc-postgresql-replication.properties资源文件提供读写和只读JDBC的配置DataSource成分:
    hibernate.dialect=org.hibernate.dialect.PostgreSQL10Dialect
    
    jdbc.url.primary=jdbc:postgresql://localhost:5432/high_performance_java_persistence
    jdbc.url.replica=jdbc:postgresql://localhost:5432/high_performance_java_persistence_replica
    
    jdbc.username=postgres
    jdbc.password=admin
    
    jdbc.url.primary属性定义主节点的 URL,而 jdbc.url.replica定义副本节点的 URL。readWriteDataSource Spring 组件定义读写 JDBC DataSourcereadOnlyDataSource组件定义只读 JDBC DataSource .

    Note that both the read-write and read-only data sources use HikariCP for connection pooling.

    actualDataSource充当读写和只读数据源的外观,并使用 TransactionRoutingDataSource 实现公用事业。readWriteDataSource使用 DataSourceType.READ_WRITE 注册键和 readOnlyDataSource使用 DataSourceType.READ_ONLY key 。
    所以,当执行读写时 @Transactional方法,readWriteDataSource将在执行 @Transactional(readOnly = true) 时使用方法,readOnlyDataSource将被使用。

    Note that the additionalProperties method defines the hibernate.connection.provider_disables_autocommit Hibernate property, which I added to Hibernate to postpone the database acquisition for RESOURCE_LOCAL JPA transactions.

    Not only that the hibernate.connection.provider_disables_autocommit allows you to make better use of database connections, but it's the only way we can make this example work since, without this configuration, the connection is acquired prior to calling the determineCurrentLookupKey method TransactionRoutingDataSource.


    构建 JPA 所需的其余 Spring 组件 EntityManagerFactory AbstractJPAConfiguration 定义基类。
    基本上,actualDataSource由 DataSource-Proxy 进一步包装并提供给 JPA EntityManagerFactory .您可以查看 source code on GitHub更多细节。
    测试时间
    为了检查事务路由是否有效,我们将通过在 postgresql.conf 中设置以下属性来启用 PostgreSQL 查询日志。配置文件:
    log_min_duration_statement = 0
    log_line_prefix = '[%d] '
    
    log_min_duration_statement属性设置用于记录所有 PostgreSQL 语句,而第二个将数据库名称添加到 SQL 日志中。
    因此,在拨打 newPost 时和 findAllPostsByTitle方法,像这样:
    Post post = forumService.newPost(
        "High-Performance Java Persistence",
        "JDBC", "JPA", "Hibernate"
    );
    
    List<Post> posts = forumService.findAllPostsByTitle(
        "High-Performance Java Persistence"
    );
    
    我们可以看到 PostgreSQL 记录了以下消息:
    [high_performance_java_persistence] LOG:  execute <unnamed>: 
        BEGIN
    
    [high_performance_java_persistence] DETAIL:  
        parameters: $1 = 'JDBC', $2 = 'JPA', $3 = 'Hibernate'
    [high_performance_java_persistence] LOG:  execute <unnamed>: 
        select tag0_.id as id1_4_, tag0_.name as name2_4_ 
        from tag tag0_ where tag0_.name in ($1 , $2 , $3)
    
    [high_performance_java_persistence] LOG:  execute <unnamed>: 
        select nextval ('hibernate_sequence')
    
    [high_performance_java_persistence] DETAIL:  
        parameters: $1 = 'High-Performance Java Persistence', $2 = '4'
    [high_performance_java_persistence] LOG:  execute <unnamed>: 
        insert into post (title, id) values ($1, $2)
    
    [high_performance_java_persistence] DETAIL:  
        parameters: $1 = '4', $2 = '1'
    [high_performance_java_persistence] LOG:  execute <unnamed>: 
        insert into post_tag (post_id, tag_id) values ($1, $2)
    
    [high_performance_java_persistence] DETAIL:  
        parameters: $1 = '4', $2 = '2'
    [high_performance_java_persistence] LOG:  execute <unnamed>: 
        insert into post_tag (post_id, tag_id) values ($1, $2)
    
    [high_performance_java_persistence] DETAIL:  
        parameters: $1 = '4', $2 = '3'
    [high_performance_java_persistence] LOG:  execute <unnamed>: 
        insert into post_tag (post_id, tag_id) values ($1, $2)
    
    [high_performance_java_persistence] LOG:  execute S_3: 
        COMMIT
        
    [high_performance_java_persistence_replica] LOG:  execute <unnamed>: 
        BEGIN
        
    [high_performance_java_persistence_replica] DETAIL:  
        parameters: $1 = 'High-Performance Java Persistence'
    [high_performance_java_persistence_replica] LOG:  execute <unnamed>: 
        select post0_.id as id1_0_, post0_.title as title2_0_ 
        from post post0_ where post0_.title=$1
    
    [high_performance_java_persistence_replica] LOG:  execute S_1: 
        COMMIT
    
    使用 high_performance_java_persistence 的日志语句前缀在主节点上执行,而使用 high_performance_java_persistence_replica 的那些在副本节点上。
    所以,一切都像魅力一样!
    所有源代码都可以在我的 High-Performance Java Persistence 中找到GitHub 存储库,因此您也可以尝试一下。
    结论
    您需要确保为连接池设置正确的大小,因为这会产生巨大的差异。为此,我建议使用 Flexy Pool .
    您需要非常勤奋,并确保相应地标记所有只读事务。只有 10% 的交易是只读的,这是不寻常的。可能是您有这样一个最多写入的应用程序,或者您正在使用只发出查询语句的写入事务?
    对于批处理,您肯定需要读写事务,因此请确保启用 JDBC 批处理,如下所示:
    <property name="hibernate.order_updates" value="true"/>
    <property name="hibernate.order_inserts" value="true"/>
    <property name="hibernate.jdbc.batch_size" value="25"/>
    
    对于批处理,您还可以使用单独的 DataSource使用不同的连接池连接到主节点。
    只需确保所有连接池的总连接大小小于 PostgreSQL 配置的连接数。
    每个批处理作业都必须使用专用事务,因此请确保使用合理的批处理大小。
    更重要的是,您希望持有锁并尽快完成事务。如果批处理器正在使用并发处理 worker,请确保关联的连接池大小等于 worker 的数量,这样它们就不会等待其他人释放连接。

    关于java - 如何使用 JPA 和 Hibernate 拆分只读和读写事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25911359/

    有关java - 如何使用 JPA 和 Hibernate 拆分只读和读写事务的更多相关文章

    1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

      我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

    2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

      总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

    3. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

      我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

    4. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

      类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

    5. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

      很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

    6. ruby - 在 Ruby 中使用匿名模块 - 2

      假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

    7. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

      我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

    8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

      关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

    9. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

      给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

    10. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

      我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

    随机推荐