我正在使用spring boot,我的任务包括调用外部API来创建资源。换句话说,它只是一个API调用,它采用一个简单的参数。
由于该调用是异步的,我需要确保创建资源。因此,如果第一次调用api失败,则必须将其排队以便在X秒后重试。一旦api调用成功完成,我必须从队列中删除该api调用。
我该如何实现这种行为?我一直在寻找使用ActiveMQ。有没有其他提案可以更好地使用弹簧靴?
答案 0 :(得分:0)
您可以使用“浏览”和“获取”。
步骤如下:
答案 1 :(得分:0)
您可以使用ActiveMQ的schedulerSupport,通过将broker schedulerSupport属性设置为true来启用它:
<broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}" schedulerSupport="true">
http://activemq.apache.org/delay-and-schedule-message-delivery.html
package com.example.amq;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ScheduledMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;
@Component
public class ProducerScheduledMessage implements CommandLineRunner {
@Autowired
private JmsTemplate jmsTemplate;
@Override
public void run(String... args) throws Exception {
send("LOCAL_Q", "send informations of first api call to do", 0);
boolean stop = false;
do {
try {
final String msg = (String) this.jmsTemplate.receiveAndConvert("LOCAL_Q");
// execute call or verify resources creation
stop = true;
} catch (Exception e) {
// if api call fails, send again to the same destination
// to be
// treated after 5 seconds
send("LOCAL_Q", "resend call api or resources creation verification to do after 5s", 5000);
}
} while (!stop);
}
public void send(String dest, final String msg, final long delay) {
this.jmsTemplate.send(dest, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
TextMessage tm = session.createTextMessage(msg);
tm.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
return tm;
}
});
}
}