习惯了将数据保存到硬盘中,放在内存中难免会让人感觉到不安全。所以本篇演示一下如何将MQ中的数据吃就好到mysql数据库中。
ActiveMQ默认的持久化数据库为kahaDB,需要添加一些配置才可以完成操作。
打开activemq.xml
做如下修改,dataSource名可以随机获取,这里使用mysql,所以使用my-ds
配置完成后,添加mysql的配置,id为上面的dataSource值,mysql数据库为activemq自行创建。
准备好mysql驱动,打开activemq安装目录下的lib文件夹,将mysql驱动拷贝到该目录下。重启activemq服务。
创建生产者类,设置DeliveryMode为DeliveryMode.PERSISTENT
package com.mq.activemq_01.jdbc;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
public class Producer {
private ConnectionFactory connectionFactory;
private Connection connection;
private Session session;
private MessageProducer messageProducer;
public Producer(){
try {
this.connectionFactory = new ActiveMQConnectionFactory( ActiveMQConnectionFactory.DEFAULT_USER,
ActiveMQConnectionFactory.DEFAULT_PASSWORD,
"tcp://localhost:61616");
this.connection = this.connectionFactory.createConnection();
this.connection.start();
this.session = this.connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
this.messageProducer = this.session.createProducer(null);
} catch (Exception e) {
// TODO: handle exception
}
}
public void send1(){
try {
Destination destination = this.session.createQueue("one");
MapMessage msg1 = this.session.createMapMessage();
msg1.setString("loginName", "zs");
msg1.setString("name", "zhangsan");
msg1.setString("password", "123456");
msg1.setInt("gender", 1);
msg1.setInt("age", 9);
msg1.setStringProperty("receiver", "A");
MapMessage msg2 = this.session.createMapMessage();
msg2.setString("loginName", "zs");
msg2.setString("name", "zhangsan");
msg2.setString("password", "123456");
msg2.setInt("gender", 1);
msg2.setInt("age", 19);
msg2.setStringProperty("receiver", "B");
MapMessage msg3 = this.session.createMapMessage();
msg3.setString("loginName", "zs");
msg3.setString("name", "zhangsan");
msg3.setString("password", "123456");
msg3.setInt("gender", 1);
msg3.setInt("age", 9);
msg3.setStringProperty("receiver", "A");
MapMessage msg4 = this.session.createMapMessage();
msg4.setString("loginName", "ls");
msg4.setString("name", "lisi");
msg4.setString("password", "123456");
msg4.setInt("age", 29);
msg4.setStringProperty("receiver", "A");
this.messageProducer.send(destination, msg1, DeliveryMode.PERSISTENT, 2, 1000*60*2);
this.messageProducer.send(destination, msg2, DeliveryMode.PERSISTENT, 3, 1000*60*2);
this.messageProducer.send(destination, msg3, DeliveryMode.PERSISTENT, 7, 1000*60*2);
this.messageProducer.send(destination, msg4, DeliveryMode.PERSISTENT, 8, 1000*60*2);
} catch (JMSException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Producer p = new Producer();
p.send1();
}
}
执行3中程序,打开mysql数据客户端
持久化内容存放在activemq_msgs表中,打开表如下
这里使用的是MapMessage存放到数据库中为blog类型