1. 程式人生 > >JMS消息發送接收舉例

JMS消息發送接收舉例

技術分享 cep 開啟 info pan jar包 ack tid ttext

1.需要的jar包

<dependency>

<groupId>org.apache.activemq</groupId>

<artifactId>activemq-all</artifactId>

<version>5.15.4</version>

</dependency>

<dependency>

<groupId>org.apache.xbean</groupId>

<artifactId>xbean

-spring</artifactId>

<version>4.8</version>

</dependency>

2.消息創建和發送QueueProducer類

package com.jmstest;

import javax.jms.Connection;

import javax.jms.ConnectionFactory;

import javax.jms.Destination;

import javax.jms.JMSException;

import javax.jms.MessageProducer;

import

javax.jms.Session;

import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class QueueProducer{

public static void main(String[] args) throws JMSException {

ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.145.129:61616");

Connection connection = connectionFactory.createConnection();

connection.start();

Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);

Destination destination = session.createQueue("ActiveMQ");

MessageProducer producter = session.createProducer(destination);

for (int i = 0; i < 3; i++) {

TextMessage message = session.createTextMessage("ActiveMQ-->" + i);

producter.send(message);

}

session.commit();

session.close();

connection.close();

}

}

3. 消息消費接收QueueConsumer類

package com.jmstest;

import javax.jms.Connection;

import javax.jms.ConnectionFactory;

import javax.jms.Destination;

import javax.jms.MessageConsumer;

import javax.jms.Session;

import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class QueueConsumer{

public static void main(String[] args) throws Exception {

//創建連接工廠並開啟

ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.145.129:61616");

Connection connection = connectionFactory.createConnection();

connection.start();

final Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);

Destination destination = session.createQueue("ActiveMQ");

MessageConsumer consumer = session.createConsumer(destination);

int i=0;

while(i <3) {

TextMessage message = (TextMessage) consumer.receive();

session.commit();

System.out.println("收到的消息:"+message.getText());

i++;

}

session.close();

connection.close();

}

}

4.執行消費端程序

技術分享圖片

5.可以從ActiveMQ控制臺看到發送的消息

技術分享圖片

JMS消息發送接收舉例