activeMQ點對點
阿新 • • 發佈:2017-11-06
ssa oca exceptio pac 開啟事務 ive mes 啟動 cal
摘要: ActiveMQ 點對點消息 Point-to-Point 是一對一
創建消息生產者
/**
* 點對點消息生產者
*
* @author Edward
*
*/
public class P2pProducer {
public static void main(String[] args) {
ConnectionFactory connectionFactory = null;
Connection conn = null;
Session session = null;
Queue queue = null;
MessageProducer messageProducer = null;
try {
// 創建工廠
// ActiveMQConnection.DEFAULT_USER 默認null
// ActiveMQConnection.DEFAULT_PASSWORD 默認null
// ActiveMQConnection.DEFAULT_BROKER_URL
// 默認failover://tcp://localhost:61616
connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_USER,
ActiveMQConnection.DEFAULT_PASSWORD,
ActiveMQConnection.DEFAULT_BROKER_URL);
// 創建連接
conn = connectionFactory.createConnection();
// 啟動連接
conn.start();
// 創建會話 createSession(true, Session.AUTO_ACKNOWLEDGE); true 表示開啟事務
// Session.AUTO_ACKNOWLEDGE 消息模式
session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
// 創建隊列
queue = session.createQueue("P2pQueue");
// 創建消息生產者
messageProducer = session.createProducer(queue);
// 創建消息
TextMessage message = session.createTextMessage();
message.setText("我是P2pProducer生產的消息");
// 發送消息
messageProducer.send(message);
// 提交事務
session.commit();
System.out.println("OK");
} catch (JMSException e) {
e.printStackTrace();
} finally {
try {
session.close();
conn.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
運行成功,查看控制臺:
創建消息消費者
/**
* 點對點消息消費者
*
* @author Edward
*
*/
public class P2pConsumer {
public static void main(String[] args) {
ConnectionFactory connectionFactory = null;
Connection conn = null;
Session session = null;
Queue queue = null;
MessageConsumer messageConsumer = null;
try {
// 創建工廠
// ActiveMQConnection.DEFAULT_USER 默認null
// ActiveMQConnection.DEFAULT_PASSWORD 默認null
// ActiveMQConnection.DEFAULT_BROKER_URL
// 默認failover://tcp://localhost:61616
connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_USER,
ActiveMQConnection.DEFAULT_PASSWORD,
ActiveMQConnection.DEFAULT_BROKER_URL);
// 創建連接
conn = connectionFactory.createConnection();
// 啟動連接
conn.start();
// 創建會話 createSession(true, Session.AUTO_ACKNOWLEDGE); false 表示不開啟事務
// Session.AUTO_ACKNOWLEDGE 消息模式
session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 創建隊列
queue = session.createQueue("P2pQueue");
// 創建消息消費者
messageConsumer = session.createConsumer(queue);
// 註冊消費消息監聽
messageConsumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
try {
System.out.println("我收到的消息:"
+ ((TextMessage) message).getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
} catch (JMSException e) {
e.printStackTrace();
}
}
}
執行結果
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
我收到的消息:我是P2pProducer生產的消息
activeMQ點對點