activemq 主从 高可用配置 加 topic 持久化

耗尽温柔 提交于 2020-08-14 05:55:22

activemq 主从 高可用配置 加 topic 持久化

参考文档:

https://blog.csdn.net/wangaiheng/article/details/79962218

https://www.cnblogs.com/nm666/p/10427622.html

zookeeper

安装zookeeper

配置zookeeper


# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just
# example sakes.
dataDir=/data/zookeeper/data
dataLogDir=/data/zookeeper/log
# the port at which the clients will connect
clientPort=2181
# the maximum number of client connections.
# increase this if you need to handle more clients
#maxClientCnxns=60
#
# Be sure to read the maintenance section of the
# administrator guide before turning on autopurge.
#
# http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance
#
# The number of snapshots to retain in dataDir
#autopurge.snapRetainCount=3
# Purge task interval in hours
# Set to "0" to disable auto purge feature
#autopurge.purgeInterval=1



配置zookeeper环境变量

vim /etc/profie

export JAVA_HOME=/usr/local/jdk/jdk1.8.0_131
export CLASSPATH=/usr/local/jdk/jdk1.8.0_131/lib/tools.jar:/usr/local/jdk/jdk1.8.0_131/lib/dt.jar

export ZOOKEEPER_HOME=/usr/local/zookeeper/zookeeper-3.4.14/
export PATH=/usr/local/mysql/bin:$ZOOKEEPER_HOME/bin:$JAVA_HOME/bin:$PATH
export PATH


启动zookeeper

zkServer.sh start


activemq

安装activemq ,一定要安装一样的版本

配置activemq.xml

<!--
    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 may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<!-- START SNIPPET: example -->
<beans
  xmlns="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.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

    <!-- Allows us to use system properties as variables in this configuration file -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>file:${activemq.conf}/credentials.properties</value>
        </property>
    </bean>

   <!-- Allows accessing the server log -->
    <bean id="logQuery" class="io.fabric8.insight.log.log4j.Log4jLogQuery"
          lazy-init="false" scope="singleton"
          init-method="start" destroy-method="stop">
    </bean>

    <!--
        The <broker> element is used to configure the ActiveMQ broker.
    -->
    <broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}">

        <destinationPolicy>
            <policyMap>
              <policyEntries>
                <policyEntry topic=">" >
                    <!-- The constantPendingMessageLimitStrategy is used to prevent
                         slow topic consumers to block producers and affect other consumers
                         by limiting the number of messages that are retained
                         For more information, see:

                         http://activemq.apache.org/slow-consumer-handling.html

                    -->
                  <pendingMessageLimitStrategy>
                    <constantPendingMessageLimitStrategy limit="1000"/>
                  </pendingMessageLimitStrategy>
                </policyEntry>
              </policyEntries>
            </policyMap>
        </destinationPolicy>


        <!--
            The managementContext is used to configure how ActiveMQ is exposed in
            JMX. By default, ActiveMQ uses the MBean server that is started by
            the JVM. For more information, see:

            http://activemq.apache.org/jmx.html
        -->
        <managementContext>
            <managementContext createConnector="false"/>
        </managementContext>

        <!--
            Configure message persistence for the broker. The default persistence
            mechanism is the KahaDB store (identified by the kahaDB tag).
            For more information, see:

            http://activemq.apache.org/persistence.html
       
        <persistenceAdapter>
            <kahaDB directory="${activemq.data}/kahadb"/>
        </persistenceAdapter> 
		-->
		
		<persistenceAdapter>
			<replicatedLevelDB directory="${activemq.data}/leveldb"
			replicas="3"
			bind="tcp://0.0.0.0:0"
			zkAddress="192.168.233.129:2181"
			hostname="192.168.233.129"
			sync="local_disk"
			zkPath="/activemq/leveldb-stores"
			/>
		</persistenceAdapter>

          <!--
            The systemUsage controls the maximum amount of space the broker will
            use before disabling caching and/or slowing down producers. For more information, see:
            http://activemq.apache.org/producer-flow-control.html
          -->
          <systemUsage>
            <systemUsage>
                <memoryUsage>
                    <memoryUsage percentOfJvmHeap="70" />
                </memoryUsage>
                <storeUsage>
                    <storeUsage limit="100 gb"/>
                </storeUsage>
                <tempUsage>
                    <tempUsage limit="50 gb"/>
                </tempUsage>
            </systemUsage>
        </systemUsage>

        <!--
            The transport connectors expose ActiveMQ over a given protocol to
            clients and other brokers. For more information, see:

            http://activemq.apache.org/configuring-transports.html
        -->
        <transportConnectors>
            
            <transportConnector name="openwire" uri="tcp://0.0.0.0:61618?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
			<!-- DOS protection, limit concurrent connections to 1000 and frame size to 100MB 
            <transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="stomp" uri="stomp://0.0.0.0:61613?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="mqtt" uri="mqtt://0.0.0.0:1883?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="ws" uri="ws://0.0.0.0:61614?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
			-->
        </transportConnectors>

        <!-- destroy the spring context on shutdown to stop jetty -->
        <shutdownHooks>
            <bean xmlns="http://www.springframework.org/schema/beans" class="org.apache.activemq.hooks.SpringContextHook" />
        </shutdownHooks>

    </broker>

    <!--
        Enable web consoles, REST and Ajax APIs and demos
        The web consoles requires by default login, you can disable this in the jetty.xml file

        Take a look at ${ACTIVEMQ_HOME}/conf/jetty.xml for more details
    -->
    <import resource="jetty.xml"/>

</beans>
<!-- END SNIPPET: example -->


启动activemq

./activemq console


检查环境

zkCli.sh
ls /
[activemq, zookeeper]

 ls /activemq/leveldb-stores
[00000000051, 00000000052]  说明当前有2个节点

get /activemq/leveldb-stores/00000000052
{"id":"localhost","container":null,"address":null,"position":-1,"weight":1,"elected":null}
cZxid = 0x146
ctime = Sun May 17 17:23:35 CST 2020
mZxid = 0x149
mtime = Sun May 17 17:23:35 CST 2020
pZxid = 0x146
cversion = 0
dataVersion = 2
aclVersion = 0
ephemeralOwner = 0x1000076591d003d
dataLength = 90
numChildren = 0
 
 elected : null ,说明它不是主节点
 
 //是主节点
 [zk: localhost:2181(CONNECTED) 11] get /activemq/leveldb-stores/00000000051
{"id":"localhost","container":null,"address":"tcp://192.168.233.1:60825","position":-1,"weight":1,"elected":"0000000051"}
cZxid = 0x142
ctime = Sun May 17 17:23:33 CST 2020
mZxid = 0x14b
mtime = Sun May 17 17:23:36 CST 2020
pZxid = 0x142
cversion = 0
dataVersion = 4
aclVersion = 0
ephemeralOwner = 0x1000076591d003c
dataLength = 121
numChildren = 0




代码测试

Producer

package com.xoby.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author :wanglei
 * @date :Created in 2020/5/17 15:21
 * @description:
 * @modified By:
 * @version: $
 */
public class Producer {

    public static final String URL = "failover:(tcp://localhost:61616," +
            "tcp://localhost:61617," +
            "tcp://192.168.233.129:61618)?randomize=true";

    public static final String queueName = "queue-test";
    public static final String topicName = "topic-test";


    public static void main(String args[]) throws JMSException {
        //1.创建ConnectionFactory
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                URL);
        //2.创建Connection
        Connection connection = connectionFactory.createConnection();
        //3.启动连接
        connection.start();
        //4.创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //5.创建一个目标
        Destination destination = session.createQueue(queueName);
        //6.创建一个生产者
        MessageProducer producer = session.createProducer(destination);
        for (int i = 0; i < 10000; i++) {
            //7.创建消息
            TextMessage message = session.createTextMessage("hello point:" + i);
            //8.发送消息
            producer.send(message);
            System.out.println("yes" + i);
        }
        //9.关闭连接
        connection.close();
    }

}



package com.xoby.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author :wanglei
 * @date :Created in 2020/5/17 15:29
 * @description:
 * @modified By:
 * @version: $
 */
public class Consumer {
    public static void main(String args[]) throws JMSException {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                Producer.URL);
        Connection connection = connectionFactory.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        connection.start();
        Queue destination = session.createQueue(Producer.queueName);
        MessageConsumer consumer = session.createConsumer(destination);
        //创建监听器
        consumer.setMessageListener(new MessageListener() {
            @Override


            public void onMessage(Message message) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    System.out.println(textMessage.getText());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
    }
}



topic 持久化

主要代码

//设置客户端id
        connection.setClientID("client-1");
         //客户端持久化订阅
        TopicSubscriber consumer = session.createDurableSubscriber(topic, "client1-sub");
       


package com.xoby.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author :wanglei
 * @date :Created in 2020/5/17 15:21
 * @description:
 * @modified By:
 * @version: $
 */
public class TopicProducer {

    public static final String URL = "failover:(tcp://localhost:61616,tcp://localhost:61617,tcp://192.168.233.129:61618)?randomize=true";

    public static final String queueName = "queue-test";
    public static final String topicName = "topic-test";


    public static void main(String args[]) throws JMSException {
        //1.创建ConnectionFactory
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                URL);
        //2.创建Connection
        Connection connection = connectionFactory.createConnection();
        //3.启动连接
        connection.start();
        //4.创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //5.创建一个目标
//        Destination destination = session.createQueue(queueName);
        Destination destination = session.createTopic(topicName);
        //6.创建一个生产者
        MessageProducer producer = session.createProducer(destination);
        for (int i = 0; i < 10; i++) {
            //7.创建消息
            TextMessage message = session.createTextMessage("hello point:" + i);
            //8.发送消息
            producer.send(message);
            System.out.println("yes" + i);
        }
        //9.关闭连接
        connection.close();
    }

}



package com.xoby.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author :wanglei
 * @date :Created in 2020/5/17 15:29
 * @description:
 * @modified By:
 * @version: $
 */
public class TopicConsumer {
    public static void main(String args[]) throws JMSException {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                Producer.URL);
        Connection connection = connectionFactory.createConnection();
        //设置客户端id
        connection.setClientID("client-1");
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        connection.start();
        //Queue destination = session.createQueue(Producer.queueName);
        Topic topic = session.createTopic(Producer.topicName);
        //客户端持久化订阅
        TopicSubscriber consumer = session.createDurableSubscriber(topic, "client1-sub");
        //创建监听器
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    System.out.println(textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }

        });
    }
}



activemq 持久化界面

说明持久化成功!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!