/src/main/java/com/udfex/ucs/amq/api/ConsumerImpl.java
Java | 77 lines | 64 code | 10 blank | 3 comment | 2 complexity | daf50bf80fdfa436d701d432e0cbe54c MD5 | raw file
- package com.udfex.ucs.amq.api;
- import com.alibaba.fastjson.JSONObject;
- import org.apache.activemq.command.ActiveMQQueue;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.jms.listener.DefaultMessageListenerContainer;
- import org.springframework.jms.listener.SessionAwareMessageListener;
- import javax.jms.*;
- /**
- * Created by Jeng on 16/1/31.
- */
- public class ConsumerImpl implements Consumer {
- private static Logger logger = LoggerFactory.getLogger(ConsumerImpl.class);
- private DefaultMessageListenerContainer messageListenerContainer;
- public DefaultMessageListenerContainer getMessageListenerContainer() {
- return messageListenerContainer;
- }
- public void setMessageListenerContainer(DefaultMessageListenerContainer messageListenerContainer) {
- this.messageListenerContainer = messageListenerContainer;
- }
- @Override
- public void subscribe(String topic, final MessageToObject messageToObject, final MessageHandler messageHandler) {
- messageListenerContainer.setDestination(new ActiveMQQueue(topic));
- messageListenerContainer.setMessageListener(new SessionAwareMessageListener<TextMessage>() {
- @Override
- public void onMessage(final TextMessage message, Session session) throws JMSException {
- MessageProducer producer = session.createProducer(message.getJMSReplyTo());
- String requestId = message.getStringProperty(BaseMessage.REQUEST_ID);
- String messageId = message.getStringProperty(BaseMessage.MESSAGE_ID);
- ConsumeResult consumeResult = new ConsumeResult();
- try {
- consumeResult.setResultCode(ConsumeResult.CONSUME_SUCCESS_CODE);
- consumeResult.setResultMsg(ConsumeResult.CONSUME_SUCCESS_DEFAULT_MESSAGE);
- DataMessage dataMessage = new DataMessage();
- dataMessage.setMessageBody(message.getText());
- dataMessage.setMessageId(messageId);
- dataMessage.setRequestId(requestId);
- if(messageHandler != null){
- messageHandler.handler(messageToObject.fromMessage(dataMessage));
- }
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- e.printStackTrace();
- consumeResult.setResultCode(ConsumeResult.CONSUME_FAIL_CODE);
- consumeResult.setResultMsg(e.getMessage());
- } finally {
- consumeResult.setMessageId(messageId);
- consumeResult.setRequestId(requestId);
- TextMessage responseMessage = session.createTextMessage(JSONObject.toJSONString(consumeResult));
- responseMessage.setStringProperty(BaseMessage.MESSAGE_ID, messageId);
- responseMessage.setStringProperty(BaseMessage.REQUEST_ID, requestId);
- producer.send(responseMessage);
- message.acknowledge();
- }
- }
- });
- }
- @Override
- public void start() {
- messageListenerContainer.initialize();
- messageListenerContainer.start();
- }
- @Override
- public void shutdown() {
- messageListenerContainer.shutdown();
- }
- }