同步异步通信

时间:2017-01-06 14:40:24

标签: java rest spring-boot ibm-mq

我有一个REST服务,它接收一些数据并通过异步IBM MQ请求检查数据。

REST控制器:

@RestController
@RequestMapping("/request")
public class RequestController {

    @RequestMapping(method = RequestMethod.POST)
    public Response postRequest(@RequestBody Request request) {

        String data = request.getData();

        jmsSender.send(data);

        // Now I need the response from MQ
        // String mqResponse = ...
        if (mqIsValid(mqResponse)) {
            return createValidResponse();
        }
        return createNotValidResponse();
    }
}

MQ发件人:

@Service
public class JmsSender {

    public void send(String data) {
        jmsTemplate.convertAndSend("QUEUE.TO.MQ", data);
    }

}

MQ接收器:

@Component
public class JmsReceiver {

    @JmsListener(destination = "QUEUE.FROM.MQ, containerFactory = "DefaultJmsListenerContainerFactory")
    public void receiveMessage(String message) {
        // How to pass the message to the controller?
    }

}

如何等待来自MQ的正确数据在控制器中创建正确的响应?

是否可以像here所描述的那样使用BlockingQueue?在我的情况下,我必须区分数据。我不能从阻塞队列中获取第一个数据。

例如,如果同时有两个REST请求(数据为abcxyz)。我怎样才能确保回答正确的答案而不仅仅是我从MQ得到的第一个答案?

我也无法更改MQ界面。

3 个答案:

答案 0 :(得分:1)

尝试使用如下的CountDownLatch。

@RestController
@RequestMapping("/request")
public class RequestController {

    @RequestMapping(method = RequestMethod.POST)
    public Response postRequest(@RequestBody Request request) {
        final CountDownLatch jmsLatch = new CountDownLatch (1);

        String data = request.getData();

        jmsSender.send(data, jmsLatch);

        try {
            latch.await();  // wait untill latch counted down to 0
        } catch (InterruptedException e) {
            return createNotValidResponse();
        }

        return createValidResponse();
    }
}

修改send方法以从控制器获取CountDownLatch。

@Service
public class JmsSender {

    public void send(String data, final CountDownLatch jmsLatch) {
        jmsLatch.await();
        jmsTemplate.convertAndSend("QUEUE.TO.MQ", data);
    }

}

修改receive方法以从控制器获取相同的CountDownLatch。

@Component
public class JmsReceiver {

    @JmsListener(destination = "QUEUE.FROM.MQ", containerFactory = "DefaultJmsListenerContainerFactory")
    public void receiveMessage(String message, final CountDownLatch jmsLatch) {
        // Pass the message to the controller
        jmsLatch.countDown();
    }

}

这里的技巧是你必须将相同的CountDownLatch实例从控制器传播到发送者和接收者类,并在收到消息后调用countDown方法。

答案 1 :(得分:0)

由于我无法找到适合自己的解决方案,因此我创建了一种简单的等待机制来获取数据。

MqReceiver:

<i class="fa fa-id-card"></i>

这可以在控制器中使用:

@Component
public class JmsReceiver {

    private final Lock lock;
    private final Condition containsKey;
    private final Map<String, String> responses;

    public JmsReceiver() {
        this.lock = new ReentrantLock();
        this.containsKey = lock.newCondition();
        this.responses = new HashMap<>();
    }

    @JmsListener(destination = "QUEUE.FROM.MQ", containerFactory = "DefaultJmsListenerContainerFactory")
    public void receiveMessage(String message) {
        put(getKeyFromMessage(message), message);
    }

    public String get(String key) throws InterruptedException {
        lock.lock();
        try {
            while (!responses.containsKey(key)) {
                containsKey.await();
            }
            return responses.get(key);
        } finally {
            lock.unlock();
        }
    }

    public void put(String key, String messagee) {
        lock.lock();
        try {
            responses.put(key, messagee);
            containsKey.signalAll();
        } finally {
            lock.unlock();
        }
    }

}

答案 2 :(得分:0)

使用jms(activemq)实现方案同步/异步的方案同步解决方案

此示例的思想是在不同的jvm中的两个不同的服务中工作。该解决方案与多个实例服务同时进行了测试:

  • 服务1(M1)-同步REST API,并在某个时候启动 使用activemq的异步流来调用实现集成模式Request-Reply的第二个服务M2。您无需停止或等待任何线程,jms模式实现了ack Session.AUTO_ACKNOWLEDGE

    @PostMapping
    public AnyDto sendMessage(final AnyDto anyDto) {
        return routeService.send(anyDto);
    }
    public void flowOrchestation (final anyDto data) throws JMSException {
        final ObjectMessage objectMessage = composeTemplateMessage(data);
        final AnyDto responseDto = jmsMessagingTemplate.convertSendAndReceive(new ActiveMQQueue("queue.request"),
                objectMessage, AnyDto.class);
    }
    private ObjectMessage composeTemplateMessage(final AnyDto data) throws JMSException {
    
        jmsTemplate.setReceiveTimeout(10000L);
        jmsMessagingTemplate.setJmsTemplate(jmsTemplate);
    
        Session session = jmsMessagingTemplate.getConnectionFactory().createConnection()
                .createSession(false, Session.AUTO_ACKNOWLEDGE);
    
        final ObjectMessage objectMessage = session.createObjectMessage(data);
    
        objectMessage.setJMSCorrelationID(UUID.randomUUID().toString());
        objectMessage.setJMSReplyTo(new ActiveMQQueue("queue.response"));
        objectMessage.setJMSExpiration(0);
        objectMessage.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
        return objectMessage;
    }
    
  

可以根据您的要求修改超时和到期时间。 0到期意味着没有时间到期。

  • 服务2(M2):只需接收消息并响应在M1上设置的JmsReplyTo。

@Component public class Consumer implements SessionAwareMessageListener<Message> { @Override @JmsListener(destination = "${queue.request}") public void onMessage(Message message, Session session) throws JMSException { AnyDto anyDto = (AnyDto) ((ActiveMQObjectMessage) message).getObject(); //do some stuff final ObjectMessage responseMessage = new ActiveMQObjectMessage(); responseMessage.setJMSCorrelationID(message.getJMSCorrelationID()); responseMessage.setObject(dtoModified); final MessageProducer producer = session.createProducer(message.getJMSReplyTo()); producer.send(responseMessage); }}