如何使用MessageListener声明队列

时间:2019-12-04 13:06:56

标签: spring-boot jms spring-jms

我使用Spring Boot 2.2,并且需要通过JMS接收消息。

我看到可以使用批注

@Component
public class JMSReceiver {

    @JmsListener(destination = "queue")
    public void receiveMessage(String message) {
        System.out.println("Received <" + message + ">");
    }
}

实施MessageListener

@Component
public class JMSReceiver implements MessageListener {

    @Override
    public void onMessage(Message message) {
       ...    
    }
}

借助MessageListener,我们如何声明使用的队列?

2 个答案:

答案 0 :(得分:1)

您不是在MessageListener实现中声明队列,而是在MessageListenerContainer中声明队列。

例如:

  @Bean
  public MessageListenerContainer messageListenerContainer() {
      DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
      container.setConnectionFactory(connectionFactory());
      container.setDestinationName("queue"); // Set the queue name here.
      container.setMessageListener(jmsReceiver()); // Your JMS receiver message listener.
      return container;
  }

答案 1 :(得分:1)

消息侦听器接口只有一种方法“ onMessage”。

public interface MessageListener {
    void onMessage(Message message);
} 

消息到达目的地后,消息使用者将通过调用消息侦听器的onMessage()方法来传递消息。注册消息侦听器使客户端可以异步接收消息,而不必阻止/轮询消息使用方。因此,我们必须在“消息使用者”中注册“消息侦听器”,因为消息是由消息使用者接收的,因此队列是在“消息使用者”中设置的(下面的示例进行了演示)这是“消息使用者”界面:

public interface MessageConsumer {
    String getMessageSelector() throws JMSException;
    MessageListener getMessageListener() throws JMSException;
    void setMessageListener(MessageListener listener) throws JMSException;
    Message receive() throws JMSException;
    Message receive(long timeout) throws JMSException;
    Message receiveNoWait() throws JMSException;
    void close() throws JMSException;
}

所以下面是可以帮助您的代码,

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

public class ConsumerMessageListener implements MessageListener {
    private String consumerName;

    public ConsumerMessageListener(String consumerName) {
        this.consumerName = consumerName;
    }

    public void onMessage(Message message) {
        TextMessage textMessage = (TextMessage) message;
        try {
            System.out.println(consumerName + " received "
                    + textMessage.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

}

在此完成队列创建,并从此处发送消息。

import java.net.URI;
import java.net.URISyntaxException;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;


import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;

public class JmsMessageListenerExample {
    public static void main(String[] args) throws URISyntaxException, Exception {
        BrokerService broker = BrokerFactory.createBroker(new URI(
                "broker:(tcp://localhost:61616)"));
        broker.start();
        Connection connection = null;
        try {
            // Producer
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                    "tcp://localhost:61616");
            connection = connectionFactory.createConnection();
            Session session = connection.createSession(false,
                    Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue("customerQueue");
            String payload = "Important Task";
            Message msg = session.createTextMessage(payload);
            MessageProducer producer = session.createProducer(queue);
            System.out.println("Sending text '" + payload + "'");
            producer.send(msg);

            // Consumer
            MessageConsumer consumer = session.createConsumer(queue);
            consumer.setMessageListener(new ConsumerMessageListener("Consumer"));
            connection.start();
            Thread.sleep(1000);
            session.close();
        } finally {
            if (connection != null) {
                connection.close();
            }
            broker.stop();
        }
    }

}

从控制器发送消息并使用Spring Boot进行接收:

@RestController
@RequestMapping("/transaction")
public class BackOfficeController {
  @Autowired private JmsTemplate jmsTemplate;
  @PostMapping("/send")
  public void send(@RequestBody BackOfficeVO transaction) {
    System.out.println("Sending a transaction.");
    // Post message to the message queue named "BackOfficeTransactionQueue"
    jmsTemplate.convertAndSend("BackOfficeTransactionQueue", transaction);
  }
}

@Component
public class BackOfficeReceiver {
  @Autowired
  private BackOfficeTransactionRepository transactionRepository;
  @JmsListener(destination = "BackOfficeTransactionQueue", containerFactory = "myFactory")
  public void receiveMessage(BackOfficeVO transaction) {
    System.out.println("Received <" + transaction + ">");
    transactionRepository.save(transaction);
  }
}

要添加,如果您正在使用现有的消息侦听器,则可以在Bean中对其进行定义:

<bean id="messageListener" class="ConsumerMessageListener"/>


<bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <property name="connectionFactory" ref="connectionFactory"/>
    <property name="destination" ref="destination"/>
    <property name="messageListener" ref="messageListener"/>
</bean>

来源: https://examples.javacodegeeks.com/enterprise-java/jms/jms-messagelistener-example/ https://dzone.com/articles/using-jms-in-spring-boot-1 https://docs.spring.io/spring/docs/5.1.7.RELEASE/spring-framework-reference/integration.html#jms-receiving-async