欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

activemq最简单的例子

程序员文章站 2022-04-13 08:48:22
...

import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
//生产者
public class Producer {
private static final String URL = “tcp://0.0.0.0:61616”;
private static final String SUBJECT = “myqueue”;
public static void main(String[] args) {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(URL);
Connection connection = null;
try {
connection = connectionFactory.createConnection();
connection.start();
//创建Session,此方法第一个参数表示会话是否在事务中执行,第二个参数设定会话的应答模式
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Destination dest = session.createQueue(SUBJECT);

        //通过session可以创建消息的生产者
        MessageProducer producer = session.createProducer(dest);
        //初始化一个mq消息
        TextMessage message = session.createTextMessage("hello active mq 中文kkkk" );
        //发送消息
        producer.send(message);
        System.out.println("send message {}....");
        session.commit();
        session.close();
    } catch (JMSException e) {
        e.printStackTrace();
    }finally {
        if(connection!=null){
            try {
                connection.close();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}

}


//消费者
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
//消费者
public class Consumer {
private static final String URL = “tcp://0.0.0.0:61616”;
private static final String SUBJECT = “myqueue”;
// private static Logger logger = LoggerFactory.getLogger(MqServer.class);
public static void main(String[] args) {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(URL);
try {
Connection connection = connectionFactory.createConnection();
connection.start();
//创建Session,此方法第一个参数表示会话是否在事务中执行,第二个参数设定会话的应答模式
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Destination dest = session.createQueue(SUBJECT);
//通过session可以创建消息的生产者
MessageConsumer messageConsumer = session.createConsumer(dest);
//接收 消息
TextMessage message = (TextMessage) messageConsumer.receive();
System.out.println(("condsumer message {} "+message.getText()));
} catch (JMSException e) {
e.printStackTrace();
}
}
}

相关标签: activemq