Activemq学习笔记(十五)JDBC方式实现master/Slave

原理

存在多个broker同时连接同一个mysql数据源,多个broker同时争抢一个mysql连接并锁定数据库操作权限,争抢到连接的称为master,其他broker称为slave,如果当前broker挂掉,另外几个继续争抢,如果挂掉的broker重连成功仍然作为slave

JDBC Master Slave 配置

使用<jdbcPersistenceAdapter/>来配置消息的持久化,自动就会使用 JDBD Master Slave的方式
 

<persistenceAdapter>

             <!-- <kahaDB directory="${activemq.data}/kahadb_2"/> -->

            <jdbcPersistenceAdapter dataSource="#activemq-db" createTablesOnStartup="true" />

        </persistenceAdapter>

useDatabaseLock 属性在此场景下禁止使用,这个是当然broker是否锁定mysql,如果不锁定,就没有意义

测试步骤:

首先消息生产者设置连接为

 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
//                "tcp://localhost:61616");
        "failover:(tcp://localhost:61616,tcp://localhost:61716)?randomize=false");

 randomize:按列表顺序调用,先发送消息到61616的broker上

然后消息61616的消费者启动程序接收

 ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection connection =  cf.createConnection();
        connection.start();

        Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("my-queue");
        MessageConsumer consumer = session.createConsumer(destination);
        int i = 0;
        while(i < 10){
            Thread.sleep(1000);
            i++;
            TextMessage message = (TextMessage)consumer.receive();
            session.commit();
            System.out.println("111接收到的消息是:"+message.getText());
        }
        session.close();
        connection.close();

  接收到几条消息后,关闭61616的broker服务器,此时系统会释放61616的锁,随后后面的61716的broker争抢到连接锁

  然后启动61716的消费者继续消费

 ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61716");
        Connection connection =  cf.createConnection();
        connection.start();

        Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("my-queue");
        MessageConsumer consumer = session.createConsumer(destination);
        int i = 0;
        while(i < 10){
            Thread.sleep(1000);
            i++;
            TextMessage message = (TextMessage)consumer.receive();
            session.commit();
            System.out.println("222接收到的消息是:"+message.getText());
        }
        session.close();
        connection.close();
    }

  消息会接着之前没有发送玩的消息继续提供给61716消费

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值