асинхронный прием сообщений в ibm mq с использованием MDB в веб-приложении springboot - PullRequest
0 голосов
/ 31 октября 2018

У меня есть приложение весенней загрузки, которое использует ibm mq для отправки и получения сообщений из другого приложения. Я написал простой код для отправки и получения сообщений с использованием библиотеки javax.jms. Все подробности о mq приведены в файле xldeploy_dictionaries.json

Код выглядит следующим образом:

добавлена ​​зависимость для mq в pom:

<dependency>
    <groupId>com.ibm.websphere</groupId>
    <artifactId>com.ibm.mqjms</artifactId>
    <version>7.5.0.4</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>com.ibm.websphere.j2ee</groupId>
    <artifactId>j2ee</artifactId>
    <version>8.5.5.3</version>
</dependency>

один класс для отправки и получения сообщений:

@Service
@Data
@Slf4j
public class MqUtil {
  private Response response;

  private String message;

  private String sendRequest(String xmlContent, Response response) throws JMSException, CusTimeoutException {
    @Cleanup
    MessageProducer sender = null;
    @Cleanup
    QueueSession session = null;
    @Cleanup
    QueueConnection connection = null;
    try {
      InitialContext ctx = new InitialContext();
      QueueConnectionFactory cf = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
      connection = cf.createQueueConnection();
      log.info(SENDING_MESSAGE_TO_MQ);
      session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      Queue queue = session.createQueue(CONST_SEND_QUEUENAME);
      sender = session.createProducer(queue);
      TextMessage txtMessage = session.createTextMessage(xmlContent);
      txtMessage.setJMSType("XML");
      connection.start();
      sender.send(txtMessage);
      log.info("Sent to MQ {}", response.getTraceId());
      String m= receiveRequestFromACBS(response, session);
      connection.close();
      return m;
    } catch (CusTimeoutException e) {
      log.error("Error occurred Timeout in queue {}", e.getMessage());
      throw new CusTimeoutException(); //custom exception
    } catch (NamingException e) {
      log.error("Error occurred sending request to Message Queue {}" + e);
      throw new CusTimeoutException();
    }
  }


  private String receiveRequest(Response response, QueueSession session)
      throws JMSException, ARATimeoutException {
    @Cleanup
    MessageConsumer receiver = null;
    try {
      this.setResponse(response);
      log.info("Receiving Message from MQ");
      Queue queueReceiver = session.createQueue(CONST_REC_QUEUENAME);
      receiver = session.createConsumer(queueReceiver);
      log.info("initializing message listener");
      receiver.setMessageListener(new TextMessageListener());
      log.info("back to receiveRequestFromACBS");
      return consumerResponse(response); //other method
    } catch (JMSException | SAXException | ParserConfigurationException | JAXBException | IOException e) {
      log.error("Error occurred while receiving request from Message Queue {}", e);
      throw new CUSTimeoutException();
    }
  }


  private String consumerResponse(Response response)
      throws IOException, JAXBException, ParserConfigurationException, SAXException, JMSException, CUSTimeoutException {

    String replyString = this.getMessage();
    ---business logic---
  }

класс прослушивателя сообщений:

@Slf4j
public class TextMessageListener implements MessageListener {    
  MqUtil MqUtil= new MqUtil();   
  @Override
  public void onMessage(Message messageReceived) {
    log.info("inside message listener");
    String replyString = "";
    try {
      if (messageReceived instanceof TextMessage) {
        log.info("Message type is text");
        replyString = ((TextMessage) messageReceived).getText();     
          xmlUtil.setMessage(replyString);

      } else {
        log.error("Invalid Message Type Received {}", messageReceived.getJMSType() + messageReceived.toString());
      }

    } catch (JMSException e) {
      log.error("error while receiving the messages {}", e.getMessage());
    }

  }
}

Я получаю следующую ошибку для этого кода - javax.jms.IllegalStateException: метод setMessageListener не разрешен.

Я понимаю, что мы не можем использовать прослушиватель сообщений для приложений j2ee, может кто-нибудь предложить другую альтернативу для асинхронного приема. Я читал, что мы можем использовать Message Driven Beans для mq, но я не знаю, с чего начать. Я пытался найти в Интернете, но я не получил хороший полный пример этого. Мне нужна помощь, чтобы узнать пошаговую процедуру отправки и получения сообщений Springboot или обычным способом для моего приложения.

...