ActiveMQ消息队列

ActiveMQ下载与部署

官网下载

http://activemq.apache.org/download.html

 

解压打开出现一下目录

 

 

启动ActiveMQ之前,记得安装JDK并配置JDK环境变量 

https://blog.csdn.net/renlianggee/article/details/90023464

JDK配置好启动ActiveMQ

启动成功 

 

打开浏览器

http://localhost:8161  默认用户名:admin,密码:admin

 

ActiveMQ消费者发送消息代码

依赖添加

        <!--activeMQ依赖-->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-client</artifactId>
            <version>5.15.11</version>
        </dependency>

Java代码实现

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class JMSProducer {
    //默认链接用户
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //默认链接密码
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //默认链接地址
    private static final String BROKER_URL = ActiveMQConnection.DEFAULT_BROKER_URL;
    //默认发送消息数
    private static final int SENDNUM = 10;

    public static void main(String[] args) {
        ConnectionFactory connectionFactory;//链接工厂
        //链接
        Connection connection=null;
        Session session;
        Destination destination;
        MessageProducer messageProducer;
        //实例化工厂
        connectionFactory = new ActiveMQConnectionFactory(JMSProducer.USERNAME, JMSProducer.PASSWORD, JMSProducer.BROKER_URL);
        try {
            connection = connectionFactory.createConnection();//通过链接工厂
            //启动链接
            connection.start();
            //Boolean.TRUE支持事务  Session.AUTO_ACKNOWLEDGE为自动确认,客户端发送和接收消息不需要做额外的工作。
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            //创建消息队列
            destination = session.createQueue("FirstQueue1");
            //创建消息生产者
            messageProducer = session.createProducer(destination);
            //发送消息
            sendMessage(session, messageProducer);
            //提交事务
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(connection!=null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    /**
     * 发送消息
     * @param session
     * @param messageProducer
     * @throws JMSException
     */
    public static void sendMessage(Session session, MessageProducer messageProducer) throws JMSException {
        for (int i = 0; i < JMSProducer.SENDNUM; i++) {
            TextMessage textMessage = session.createTextMessage("发送消息:" + "ActiveMQ 发送的消息" + i);
            System.out.print("发送消息:" + "ActiveMQ 发送的消息" + i);
            messageProducer.send(textMessage);
        }
    }
}

代码结果查看 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章