Java 连接active mq

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maiyikai/article/details/77198822

使用mq,首先要有环境,所以安装和打开的教程在这:http://blog.csdn.net/maiyikai/article/details/77197776
为了数据的安全,建议加入访问mq用户的限制,可以操作mq的配置文件,路径 apache-activemq-5.15.0\conf 下的activemq.xml,添加配置:

<!-- 添加访问ActiveMQ的账号密码 -->  
        <plugins>  
            <simpleAuthenticationPlugin>  
                <users>  
                    <authenticationUser username="admin" password="admin123" groups="users,admins"/>  
                </users>  
            </simpleAuthenticationPlugin>  
        </plugins>

加入之后:
新增配置

然后,使用代码访问的时候,用户名和密码必须是配置中的,不然拒绝访问。
这里使用maven构建java工程(队列式):
首先导入依赖包(操作文件pom.xml):

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>MQ</groupId>
  <artifactId>MQ</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>MQ</name>
  <url>http://maven.apache.org</url>

    <properties>
        <java.version>1.8</java.version>
        <mybatis.spring.version>1.2.4</mybatis.spring.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-all</artifactId>
      <version>5.15.0</version>
    </dependency>
  </dependencies>
</project>

信息的发送者创建及信息的发送(操作文件Sende.java):

public class Sender {

    public static void main(String[] args) {
         //连接工厂,JMS 用它创建连接
        ConnectionFactory connectionFactory;
        //JMS 客户端到JMS Provider 的连接
        Connection connection = null;
        // 一个发送或接收消息的线程
        Session session;
        //消息的目的地;消息发送给谁.
        Destination destination;
        // 消费者,消息接收者
        MessageProducer messageProducer;
        try {
            connectionFactory = new ActiveMQConnectionFactory("admin", "admin123", "tcp://10.9.2.254:61616");//用户名密码必须和activemq.xml中的用户名和密码一致,否则不能连接
            // 构造从工厂得到连接对象
            connection = connectionFactory.createConnection();//从工厂创建一个连接

            connection.start();//开启
             // 创建一个session,
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个队列,队列名随意定义
            destination = session.createQueue("FirstQueuess");//队列式
            //destination = session.createTopic("mmm");//主题式
            // 获取消息生成者
            messageProducer = session.createProducer(destination);
            // 设置持久化,此处学习,根据需要设置
            messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
            //消息发布--队列形式

            //发送100条信息
            for(int i = 0 ; i < 100 ; i ++){
                 // 发送消息到目的地方
                TextMessage tm = session.createTextMessage("发送的信息 "+i);
                System.out.println("发送的信息 "+i);
                messageProducer.send(tm);
            }
            session.commit();

        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                if(connection != null){
                    connection.close();//
                }
            } catch (JMSException e) {
                System.out.println("----");
            }
        }
    }
}

tcp://10.9.2.254:61616 这串地址中的端口61616是mq消息发送与订阅的”通道“。
如果是本机测试,也不需要对用户的限定,那么可以使用默认的值去替代:

connectionFactory = new ActiveMQConnectionFactory(
                    ActiveMQConnectionFactory.DEFAULT_USER
                    ,ActiveMQConnectionFactory.DEFAULT_PASSWORD
                    ,ActiveMQConnectionFactory.DEFAULT_BROKER_URL);

生产者就写完了。
消费者的书写和生产者几乎一样,也是要创建连接工厂,然后产生连接,再进行消息的接收(操作文件:Receive.java):

public class Receiver {
    public static void main(String[] args) {
        ConnectionFactory connectionFactory;
        Connection connection = null;
        Session session;
        Destination destination;
        MessageConsumer messageConsumer ;

        //连接工厂要和生产者一致
        connectionFactory = new ActiveMQConnectionFactory("admin"/*ActiveMQConnection.DEFAULT_USER*/,
                "admin123"/*ActiveMQConnection.DEFAULT_PASSWORD*/, "tcp://localhost:61616");

        try {
            connection = connectionFactory.createConnection();
            connection.start();

            session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
            //使用的队列和生产者定义的一致,才能接收生产者发送的消息
            destination = session.createQueue("FirstQueuess");
            //destination = session.createTopic("mmm");//主题式
            messageConsumer = session.createConsumer(destination);
            //这里一次性全部获取
            while(true){
                TextMessage tm = (TextMessage) messageConsumer.receive(500000);
                if(tm != null){
                    System.out.println("1收到信息:"+tm.getText());
                }
            }
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {  
            try {  
                if (null != connection)  
                    connection.close();  
            } catch (Throwable ignore) {  
            }  
        }  
    }
}

在写代码的过程中。一般地,由消费者进行订阅,再有生产者发布。才能实现消费者可以实时获取生产者发布的消息。

得到的结果:

1收到信息:发送的信息 0
1收到信息:发送的信息 1
1收到信息:发送的信息 2
1收到信息:发送的信息 3
1收到信息:发送的信息 4
1收到信息:发送的信息 5
.
.
.
1收到信息:发送的信息 100

可以定义多个消费者进行消息消费。

多个消费者消费队列式消息,每个消费者获取到的消息都不可能相同。直到队列里的消息被消费完。
多个消费者消费主题式消息,每个消费者获取的消息都是一样的,一次性消费。

注:生产队列式的消息,只能用队列式的消费;生产主题式的消息,只能用主题消费。

猜你喜欢

转载自blog.csdn.net/maiyikai/article/details/77198822
今日推荐