Spring Boot with JMS - ActiveMQ(2)

本篇介结Spring Boot JMS ActiveMQ 实现双向消息对列。

1. 修改上篇文章的Consumer.java代码,加入@SendTo("return.queue"),修改processMessage(String content) 方法,如下:

package com.spring.boot.jms.consumer;

import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;

/**
 * Description: 消息消费者
 * author: 慢慢来了
 * date:  2017/3/23 14:07
 */
@Component
public class Consumer {

    @JmsListener(destination = "msg.p2p.queue")
    @SendTo("return.queue")
    public String processMessage(String content) {

        System.out.println("Receiving a message :" + content);
        return "return mesage" + content;
    }


}

  1. 在Producter.java中新增 receivingMsg(String content)方法,并加入监听@JmsListener(destination = "return.queue")如下:
package com.spring.boot.jms.producter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.jms.Destination;
import java.time.Instant;

/**
 * Description: 消息生产者
 * author: 慢慢来了
 * date:  2017/3/23 14:07
 */
@Component
public class Producter{

    @Autowired
    private JmsMessagingTemplate jmsTemplate;

    public void sendMessage(Destination destination, final String message) {
        jmsTemplate.convertAndSend(destination, message);
    }


    @JmsListener(destination = "return.queue")
    public void receivingMsg(String content){
        System.out.println(Instant.now().getEpochSecond() + " -Receiving a message : " +  content);
    }

}

启动单测试(代码跟上篇一样没变),如下:

package com.spring.boot.jms;

import com.spring.boot.jms.producter.Producter;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.jms.Destination;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpirngBootJmsApplicationTests {

    @Autowired
    private Producter producter;

    @Test
    public void contextLoads() {
        Destination p2pMsg = new ActiveMQQueue("msg.p2p.queue");

        producer.sendMessage(p2pMsg , "hello , this is jms msg");

    }

}

结果如下:

Spring Boot with JMS - ActiveMQ(2)_第1张图片
Paste_Image.png
Spring Boot with JMS - ActiveMQ(2)_第2张图片
Paste_Image.png

下篇开始介绍ActiveMQ Topics消息发送也接收。

你可能感兴趣的:(Spring Boot with JMS - ActiveMQ(2))