以指定速率处理来自rabbitmq的消息
我们一直在尝试让侦听器以1 msg/2秒的特定速率从rabbitmq读取消息。到目前为止,我们还没有在rabbit mq中找到任何这样的实用程序。因此,考虑使用DB执行此操作,即侦听器将读取消息并将其存储到DB中,然后调度器将以所需的速率从DB中处理。如果有更好的方法,请提出建议。我们正在春季开发我们的应用程序。提前谢谢 你不能用一个监听器来做,但你可以用一个以指定速率处理来自rabbitmq的消息,rabbitmq,spring-amqp,throttling,spring-rabbit,Rabbitmq,Spring Amqp,Throttling,Spring Rabbit,我们一直在尝试让侦听器以1 msg/2秒的特定速率从rabbitmq读取消息。到目前为止,我们还没有在rabbit mq中找到任何这样的实用程序。因此,考虑使用DB执行此操作,即侦听器将读取消息并将其存储到DB中,然后调度器将以所需的速率从DB中处理。如果有更好的方法,请提出建议。我们正在春季开发我们的应用程序。提前谢谢 你不能用一个监听器来做,但你可以用一个rabbitmplate来做 @SpringBootApplication public class So40446967Applicat
rabbitmplate来做
@SpringBootApplication
public class So40446967Application {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(So40446967Application.class, args);
RabbitAdmin admin = context.getBean(RabbitAdmin.class);
AnonymousQueue queue = new AnonymousQueue();
admin.declareQueue(queue);
RabbitTemplate template = context.getBean(RabbitTemplate.class);
for (int i = 0; i < 10; i++) {
template.convertAndSend(queue.getName(), "foo" + i);
}
String out = (String) template.receiveAndConvert(queue.getName());
while (out != null) {
System.out.println(new Date() + " " + out);
Thread.sleep(2000);
out = (String) template.receiveAndConvert(queue.getName());
}
context.close();
}
}
@springboot应用程序
公共类SO40446967应用程序{
公共静态void main(字符串[]args)引发异常{
ConfigurableApplicationContext上下文=SpringApplication.run(So40446967Application.class,args);
RabbitAdmin=context.getBean(RabbitAdmin.class);
AnonymousQueue=新建AnonymousQueue();
管理员申报(队列);
RabbitTemplate=context.getBean(RabbitTemplate.class);
对于(int i=0;i<10;i++){
convertAndSend(queue.getName(),“foo”+i);
}
String out=(String)template.receiveAndConvert(queue.getName());
while(out!=null){
System.out.println(新日期()+“”+out);
《睡眠》(2000年);
out=(字符串)template.receiveAndConvert(queue.getName());
}
context.close();
}
}
当然,您可以使用更复杂的任务调度程序或Spring@Async
方法,而不是睡眠。受Gary Russel答案启发:
您可以使用更复杂的工具,如任务调度器或Spring@Async
您还可以获得每分钟确定的消息数,并模拟相同的限制速率:
private final RabbitTemplate rabbitTemplate;
@Scheduled(fixedDelay = 60000) // 1 minute
public void read() {
List<String> messages = new ArrayList<>();
String message = getMessageFromQueue();
while(message != null && messages.size() < 30) { // 30 messages in 1 minute = 1 msg / 2 seconds
messages.add(message);
message = getMessageFromQueue();
}
public String getMessageFromQueue() {
return (String) rabbitTemplate.receiveAndConvert(QUEUE_NAME);
}
}
private final rabbitmplate rabbitmplate;
@计划(固定时间=60000)//1分钟
公共无效读取(){
列表消息=新建ArrayList();
字符串消息=getMessageFromQueue();
而(message!=null&&messages.size()<30){//30条消息在1分钟内=1 msg/2秒
消息。添加(消息);
message=getMessageFromQueue();
}
公共字符串getMessageFromQueue(){
返回(字符串)rabbitmplate.receiveAndConvert(队列名称);
}
}