【ActiveMQ笔记三】ActiveMQ请求响应模式

请求响应模式的主要应用场景:确定mq有没有正确的消费消息。
基础环境,参见笔记一

 我们实际中的很多应用相当于一种一应一答的过程,需要双方都能给对方发送消息。于是请求-应答的这种通信方式也很重要。它也应用的很普遍。
注意:请求-应答方式并不是JMS规范系统默认提供的一种通信方式。
在这里插入图片描述
简单的说就是一来一回

  1. 首先,我们定义一个producer
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class ProducerB {

    @Autowired
    private JmsTemplate jmsTemplate;

    @Test
    public void testReplyTo() throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            jmsTemplate.convertAndSend("springboot.replyto.queue", i);
        }
        Thread.sleep(1);
    }
}
  1. 然后定义一个接受者,接受者收到消息之后,要通知发送者,通过@SendTo
@Component
public class ConsumerR {

    @JmsListener(destination = "springboot.replyto.queue")
    @SendTo("out.replyTo.queue")
    public String receiveQueue(String text) {
        System.out.println(this.getClass().getName()+" 收到的报文为==>:"+text);
        return text + ":" + "check";
    }
}

因此,Producer也是一个Consumer,在Producer服务中定义一个监听,接收ConsumerR返回的消息

@Service
public class ProducerR {

    @JmsListener(destination = "out.replyTo.queue")
    public void consumerMessage(String text){
        System.out.println("从out.replyTo.queue收到报文==>"+text);
    }
}

运行测试脚本

com.good.mq.activemq.queue.ConsumerR 收到的报文为==>:0
从out.replyTo.queue收到报文==>0:check
com.good.mq.activemq.queue.ConsumerR 收到的报文为==>:1
从out.replyTo.queue收到报文==>1:check
com.good.mq.activemq.queue.ConsumerR 收到的报文为==>:2
从out.replyTo.queue收到报文==>2:check

源码地址

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