1.修改conf/activemq.xml文件,添加一下配置
<persistenceAdapter>
<jdbcPersistenceAdapter dataDirectory="${activemq.base}/data" dataSource="#dataSource"/>
</persistenceAdapter>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/activeMQ?relaxAutoCommit=true"></property> <property name="username" value="root"></property> <property name="password" value="****"></property> <property name="poolPreparedStatements" value="true"></property> </bean>
2.将dbcp和jdbc驱动拷到activeMQ的lib目录下
3.以下代码实现
package com.suobei.activeMQ; import org.apache.activemq.ActiveMQConnectionFactory; import org.junit.Test; import javax.jms.*; /** * topic消息持久化订阅,持久到mysql * Created by wangmin on 2018/3/12 0012. */ public class TopicPersistentMysqlTest { /** * 编写消息的发送方,生产者 */ @Test public void test1() throws JMSException { //1.创建连接工厂对象 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://www.itroot.top:61616"); //2.获取连接对象 Connection connection = connectionFactory.createConnection(); System.out.println(connection); //3.连接MQ服务 connection.start(); //4.获得session Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); //5.通过session创建主题 Topic topic = session.createTopic("itRootTopic"); //6.通过session对象创建消息的消费者 MessageProducer messageProducer = session.createProducer(topic); //7.创建一条消息 TextMessage textMessage = session.createTextMessage("起床了...啦啦啦"); //8.发送消息 messageProducer.send(textMessage,DeliveryMode.PERSISTENT,1,1000*60*60*24); //关闭资源 messageProducer.close(); session.close(); connection.close(); } /** * 消息的消费者,接收方 * @throws JMSException */ @Test public void test2() throws JMSException { //1.创建连接工厂对象 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://www.itroot.top:61616"); //2.获取连接对象 Connection connection = connectionFactory.createConnection(); //设置客户端id connection.setClientID("client-1"); //3.连接MQ服务 connection.start(); //4.获得session final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); //5.通过session创建主题 Topic topic = session.createTopic("itRootTopic"); //6.通过session对象创建持久化消息的消费者 TopicSubscriber consumer = session.createDurableSubscriber(topic, "client1-sub"); consumer.setMessageListener(message -> { //当我们监听的topic中存在消息时,这个方法自动执行 TextMessage textMessage= (TextMessage) message; try { System.out.println("接收到消息:"+textMessage.getText()); } catch (JMSException e) { e.printStackTrace(); } }); while (true){ } } }