- activemq的基本的消息发送操作:
package com.paic.mq;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* 发送Activemq消息队列
*/
public class Producer {
private static final String URL="tcp://127.0.0.1:61616";
private static final String QUEUE_ANME="MY_FIRST QUEUE";
public static void main(String[] args) throws JMSException {
//1.创建服务链接工厂,使用默认的用户名和密码 admin/admin
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(URL);
//2.创建连接对象
Connection connection = factory.createConnection();
connection.start();
/**
* false: 是否开启事务,如果是false,则消息会被直接提交至队列中
* true: 表示开启事务,开启事务之后,需要显示提交事务/session.commit();
* Session.AUTO_ACKNOWLEDGE: 签收
*/
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//创建队列
Queue queue = session.createQueue(QUEUE_ANME);
MessageProducer producer = session.createProducer(queue);
//发送具体的业务消息数据
for (int i = 1; i <= 3; i++) {
//消息体
TextMessage textMessage = session.createTextMessage("this is sync "+i+" jj message");
//将消息发送到MQ
producer.send(textMessage);
}
//关闭资源
producer.close();
session.close();
connection.close();
System.out.println("******* message send over ************");
}
}
消息的消费者:
package com.paic.mq;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
public class Consumer {
private static final String URL = "tcp://127.0.0.1:61616";
private static final String QUEUE_NAME = "MY_FIRST QUEUE";
public static void main(String[] args) throws JMSException {
//1.创建工厂对象
ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(URL);
//2.创建链接对象
Connection connection = activeMQConnectionFactory.createConnection();
connection.start();
//3.创建会话对象
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//4.创建队列对象
Queue queue = session.createQueue(QUEUE_NAME);
//5.创建消费者
MessageConsumer consumer = session.createConsumer(queue);
while (true){
TextMessage message = (TextMessage) consumer.receive();
if (message != null) {
String text = message.getText();
System.out.println(text);
} else {
break;
}
}
consumer.close();
session.close();
connection.close();
}
}
- 生产者的事务介绍:
true: 表示显示的开启事务,既然是显示的开启,则需要在会话中显示的提交事务/session.commit();
如果没有commit();则消息不会入队列
false: 表示不开启事务,消息会直接进入队列中.
注意:当参数为true的时候,消息会先进入缓冲区,批量处理 - 既然有commit(),则必然有rollback();
假设这一批次的消息中间有某条消息发生错误,则进行回滚操作.
try{
/**
* 1. 消息正常的话,直接进行commit就行
* 2. 中间某条消息异常,进行rollback();
*/
session.commit();
}catch (Exception e){
session.rollback();
}
- 消费者事务:
同理,在消费侧,如果是开启事务true,则必须调用commit();
否则消息中间件不认为该消息被消费了,就会出现消息被重复消息
的情况.