ActiveMQ Configuring JDBC Master-Slave

Source: Internet
Author: User
Tags rollback

Using JDBC to configure master-slave mode, persistent messages are stored in the database.

At the same time, only one master Broker,master accepts the client connection, and slave does not accept the connection.
When Master is offline due to shutdown, one of the slave is promoted to master, and then the client connection is accepted. But the original master's non-persistent message was lost, and the persistent message was saved in the database.

Broker XML configuration: Using MySQL data source

<!--Licensed to the Apache software Foundation (ASF) under one or more contributor license agreements.    See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License");  You are not a use of this file except in compliance with the License. Obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 unless required by applicab Le law or agreed into writing, software distributed under the License is distributed on a "as is" BASIS, without W    Arranties or CONDITIONS of any KIND, either express OR implied. See the License for the specific language governing permissions and limitations under the License. -<!--Use the JDBC for message persistence for more information, see:http://activemq.apache.org/persistence.htm    L need to add Derby database to your classpath in order to make this example work.  Download it from Http://db.apache.org/derby/and put it in the ${activemq_home}/lib/optional/folder optionally you can Configure any and RDBM as shown below to run ActiveMQ with this configuration add Xbean:conf/activemq-jdbc.xml t o your command e.g. $ BIN/ACTIVEMQ xbean:conf/activemq-jdbc.xml -<Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.0.xsd Http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/ Activemq-core.xsd ">    <BrokerUSEJMX= "false"Brokername= "Jdbcbroker"xmlns= "Http://activemq.apache.org/schema/core">    <Persistenceadapter>       <JdbcpersistenceadapterdataDirectory= "${activemq.base}/data"DataSource= "#mysql-ds"/>    </Persistenceadapter>    <transportconnectors>       <Transportconnectorname= "Default"URI= "tcp://0.0.0.0:61616"/>    </transportconnectors>  </Broker>   <!--Embedded Derby DataSource Sample Setup - <!--<bean id= "Derby-ds" class= "Org.apache.derby.jdbc.EmbeddedDataSource" > <property name= "DatabaseName" Value= "Derbydb"/> <property name= "CreateDatabase" value= "create"/> </bean> -   <!--Postgres DataSource Sample Setup -  <!--<bean id= "Postgres-ds" class= "Org.postgresql.ds.PGPoolingDataSource" > <property name= "ServerName" value= "localhost"/> <property name= "databaseName" value= "Activemq"/> <property name= "portnumber" value= " 0 "/> <property name=" user "value=" activemq "/> <property name=" password "value=" Activemq "/> <pro  Perty name= "DataSourceName" value= "Postgres"/> <property name= "initialconnections" value= "1"/> <property Name= "MaxConnections" value= "ten"/> </bean> -  <!--MySql DataSource Sample Setup -  <BeanID= "Mysql-ds"class= "Org.apache.commons.dbcp.BasicDataSource"Destroy-method= "Close">    < Propertyname= "Driverclassname"value= "Com.mysql.jdbc.Driver"/>    < Propertyname= "url"value= "Jdbc:mysql://192.168.40.8:3306/db_zhang?relaxautocommit=true"/>    < Propertyname= "username"value= "root"/>    < Propertyname= "Password"value= "root"/>    < Propertyname= "Maxactive"value= "$"/>    < Propertyname= "Poolpreparedstatements"value= "true"/>  </Bean>  <!--Oracle DataSource Sample Setup -  <!--<bean id= "Oracle-ds" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" > < Property Name= "Driverclassname" value= "Oracle.jdbc.driver.OracleDriver"/> <property name= "url" value= "Jdbc:o  Racle:thin: @localhost: 1521:amqdb "/> <property name=" username "value=" Scott "/> <property name=" Password " Value= "Tiger"/> <property name= "maxactive" value= "$"/> <property name= "poolpreparedstatements" value= "True"/> </bean> -</Beans>

Client configuration, producer and consumer are the same:

New Activemqconnectionfactory ("Failover: (tcp://localhost:61616,tcp://localhost:61618)");

As an example of MySQL database, 3 tables are created in MySQL after the broker is started:
ACTIVEMQ_MSGS Storing persistent messages
There is only one record in the Activemq_lock table, and the broker executes a SELECT * from the Activemq_lock for UPDATE acquires the lock, the broker that acquires the lock is the master
Activemq_acks

The call stack for the broker to get the lock is as follows:

//Org.apache.activemq.store.jdbc.DefaultDatabaseLocker Public voidDostart ()throwsException {log.info ("Attempting to acquire the exclusive lock to become the Master broker"); //SELECT * from Activemq_lock for UPDATEString sql =getstatements (). Getlockcreatestatement (); Log.debug ("Locking Query is" +SQL);  while(true) {        Try{Connection=datasource.getconnection (); Connection.setautocommit (false); Lockcreatestatement=connection.preparestatement (SQL); //Execute SELECT * from Activemq_lock for UPDATE//If successful, jump out of the loop. Throws an exception if it is timed outLockcreatestatement.execute ();  Break; } Catch(Exception e) {Try {                if(Isstopping ()) {Throw NewException ("Cannot start broker as being asked to shut." + "interrupted attempt to acquire Lock:" +e, E); }                if(Exceptionhandler! =NULL) {                    Try{exceptionhandler.handle (e); } Catch(Throwable handlerexception) {log.error ("The exception handler" +Exceptionhandler.getclass (). Getcanonicalname ()+ "Threw this exception:" +handlerexception+ "while trying-handle this exception:" +e, handlerexception); }                } Else{log.debug ("Lock failure:" +e, E); }            } finally {                //Let's make sure the database connection is properly//closed When a error occurs so the we ' re not leaking//Connections                if(NULL!=connection) {                    Try{connection.rollback (); } Catch(SQLException E1) {Log.debug ("Caught exception during rollback on connection:" +E1, E1); }                    Try{connection.close (); } Catch(SQLException E1) {Log.debug ("Caught exception while closing connection:" +E1, E1); } Connection=NULL; }            }        } finally {            if(NULL!=lockcreatestatement) {                Try{lockcreatestatement.close (); } Catch(SQLException E1) {Log.debug ("Caught while closing statement:" +E1, E1); } lockcreatestatement=NULL; }} log.info ("Failed to acquire lock. Sleeping for "+ Lockacquiresleepinterval +" milli (s) before trying again ... "); Try{thread.sleep (lockacquiresleepinterval); } Catch(Interruptedexception IE) {Log.warn ("Master Lock retry Sleep interrupted", IE); }} log.info ("Becoming the Master on DataSource:" +dataSource);}

The broker performs a SELECT * from Activemq_lock for UPDATE to get the lock, gets a success, then becomes master, and if it fails, continues to acquire the lock after a period of sleep.

The exception that is thrown when timed out:

ActiveMQ Configuring JDBC Master-Slave

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.