ActiveMQ通过JmsTemplate来发送接收消息

添加activemq依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>

配置文件配置消息队列的地址

spring:
  activemq:
#    broker地址 两个单机配置:failover:(tcp://localhost:61616,tcp://localhost:61617)?randomize=true
    broker-url: tcp://127.0.0.1:61616
    pool:
      max-connections: 100
  jms:
#    采用队列模式为false,主题模式为true
    pub-sub-domain: false
    cache:
      session-cache-size: 100
    template:
      receive-timeout: 100
#      是否持久化
      delivery-mode: persistent

生产者代码(入参是队列名和消息)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

@Service
public class ProducerService {

    @Autowired
    private JmsTemplate jmsTemplate;

    public void sendMessage(String destination, final String msg){
        System.out.println(Thread.currentThread().getName()+" 向队列"+destination.toString()+"发送消息---------------------->"+msg);
        jmsTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }

}

消费者监听队列接收消息(注解是队列名)

import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.*;

@Component
@EnableJms
public class ConsumerListener implements MessageListener {

    @Override
    @JmsListener(destination = "demoQueueDestination1")
    public void onMessage(Message message) {
        String msg = null;
        try {
            msg = ((TextMessage)message).getText();
        } catch (JMSException e) {
            e.printStackTrace();
        }
        System.out.println("listen:"+msg);
    }
}

消费者手动接收消息(入参是队列名)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.TextMessage;

@Service
public class ConsumerService {
    @Autowired
    private JmsTemplate jmsTemplate;

    public String receive(String destination) throws JMSException,NullPointerException {
        TextMessage textMessage = (TextMessage) jmsTemplate.receive(destination);
        String text = textMessage.getText();
        System.out.println("从队列" + destination.toString() + "收到了消息:\t" + text);
        return text;
    }
}

你可能感兴趣的:(MQ)