gpt4 book ai didi

java - 有没有更好的方法使用rabbitMQ消费多线程消息?

转载 作者:行者123 更新时间:2023-12-02 09:50:10 24 4
gpt4 key购买 nike

我目前正在学习如何使用 RabbitMQ 来调度和分派(dispatch)作业到不同的 VM。我现在在工作端工作。 VM上的worker需要执行一些硬加载作业,如果成功完成则返回到服务器。

我在官方api和这里做了一些调查,试图测试它是否可以工作。

Connection connection = factory.newConnection();
final Channel channel = connection.createChannel();
channel.basicQos(10);
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, final Envelope envelope, AMQP.BasicProperties properties, final byte[] body) throws IOException {
Thread th = new Thread() {public void run() {
try{
//do some jobs here...
synchronized (this) {channel.basicAck(envelope.getDeliveryTag(), false);}
} catch (Exception e) {
e.printStackTrace();
try {
synchronized (this) {channel.basicReject(envelope.getDeliveryTag(), false)}
} catch (IOException e1) {e1.printStackTrace();}
}
};
th.start();
}
};
channel.basicConsume(queueName, false, consumer);

这段代码对我有用。但我只是想知道是否有更好且线程安全的方法来做到这一点。

最佳答案

使用 ExecutorService 怎么样?而不是为每条消息创建一个新线程?根据传入消息的速率,您的方法创建的线程数量可能会很快增长得非常大,这可能会降低您的服务。

关于java - 有没有更好的方法使用rabbitMQ消费多线程消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56370757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com