消息队列(MQ)入门-activemq,代码级别

第一种:activemq:

    1、从官网下载apache-activemq-5.15.3-bin.zip并解压;

    2、启动activemq, CMD--/bin/activemq start ,访问127.0.0.1:8161/ 用户名密码都默认为admin;

    3、新建java工程,引入jar包;可以在解压的文件夹中获取如下jar包:

消息队列(MQ)入门-activemq,代码级别

4、开始写代码测试;

1、生产者消费者模式(p2p模式):

  生产者代码

消息队列(MQ)入门-activemq,代码级别

消息队列(MQ)入门-activemq,代码级别

package com.acmq.test.p2p; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; public class Sender { private static final int SEND_NUMBER = 5; static DateFormat df = new SimpleDateFormat("HH:mm:ss:SSS"); static ConnectionFactory connectionFactory; static Connection connection = null; static Session session; static Destination destination; static MessageProducer producer; public static void main(String[] args) { connectionFactory = new ActiveMQConnectionFactory( ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, "tcp://localhost:61616"); try { connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue("duilie"); producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); sendMessage(session, producer); session.commit(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != connection) connection.close(); } catch (Throwable ignore) { } } } public static void sendMessage(Session session, MessageProducer producer) throws Exception { for (int i = 1; i <= SEND_NUMBER; i++) { TextMessage message = session.createTextMessage(" 发送的消息" + i); System.out.println(df.format(new Date())+"发送消息:" + "ActiveMq 发送的消息" + i); Thread.sleep(3000); producer.send(message); } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zydsxj.html