ActiveMQの(ⅱ) - インストールと基本的な使用のActiveMQ

まず、インストール
ActiveMQの(ⅱ) - インストールと基本的な使用のActiveMQ
に成功した後に開始
ActiveMQの(ⅱ) - インストールと基本的な使用のActiveMQ

第二に、テスト用のActiveMQのインスタンスを作成します

  • 必要な構成Mavenの依存
    <dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-all</artifactId>
    <version>5.9.0</version>
    </dependency>
    <dependency>
    <groupId>org.apache.xbean</groupId>
    <artifactId>xbean-spring</artifactId>
    <version>3.16</version>
    </dependency>
  • メッセージを送ります

    public class QueueSender {
    public static void main(String[] args) throws Exception{
        //连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection connection = connectionFactory.createConnection();
        connection.start();
    
        //带事务的session
        Session session = connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("my-queue");
        MessageProducer producer = session.createProducer(destination);
    
        for (int i = 0; i < 3; i++) {
            TextMessage message = session.createTextMessage("message--"+i);
            Thread.sleep(1000);
            //通过消息生产者发出消息
            producer.send(message);
        }
        session.commit();
        session.close();
        connection.close();
    }
    }

メインコンソール出力を操作する方法:

ActiveMQの(ⅱ) - インストールと基本的な使用のActiveMQ

このメッセージは、それを行くその送られ?
ActiveMQの(ⅱ) - インストールと基本的な使用のActiveMQ

  • メッセージを受信します

    public class QueueReceive {
    public static void main(String[] args) throws Exception{
        //连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection connection = connectionFactory.createConnection();
        connection.start();
    
        //带事务的session,并且自动签收
        final Session session = connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("my-queue");
        MessageConsumer consumer = session.createConsumer(destination);
    
        int i = 0;
        while (i<3){
            i++;
            TextMessage message = (TextMessage) consumer.receive();
            session.commit();
            System.out.println("收到的消息是:"+message.getText());
        }
        session.close();
        connection.close();
    }
    }

    mainメソッドを実行します
    ActiveMQの(ⅱ) - インストールと基本的な使用のActiveMQ

サーバが受信したメッセージが処理される送信に続いて見てください。
ActiveMQの(ⅱ) - インストールと基本的な使用のActiveMQ

おすすめ

転載: blog.51cto.com/mazongfei/2415479
おすすめ