gpt4 book ai didi

java - 多线程环境中 RabbitMQ 的性能问题

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

我有两个简单的测试用例。在第一个中,我重用了连接和 channel 。在第二个中,我仅重用连接。使用第二个的原因只是为了模拟多线程环境中每个线程的 channel 场景(这并不完全相同,但我们可以了解性能)

因此,从第一个开始,我可以发布 70000 条消息/秒,从第二个开始,我只能发布 1500 条消息/秒。

  1. 这是否意味着在 RabbitMQ 中创建 channel 的成本很高?
  2. 我们可以使用 channel 池来解决这个问题吗?

第一个示例

public class Send {

public static void main(String[] args) throws Exception {

ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("myExchange", "direct", true);
channel.queueDeclare("myQueue", true, false, false, null);

for (int i = 0; i < 1000000; i++) {
String message = "{\"id\" : \"56664f85-62e0-11e5-a74b-59530fbb6d8d\"" + i + "}";
channel.basicPublish("", "myQueue", null, message.getBytes("UTF-8"));
}

channel.close();
connection.close(); }

第二个示例

public class Send {

public static void main(String[] args) throws Exception {

ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();

for (int i = 0; i < 1000000; i++) {
Channel channel = connection.createChannel();
channel.exchangeDeclare("myExchange", "direct", true);
channel.queueDeclare("myQueue", true, false, false, null);
String message = "{\"id\" : \"56664f85-62e0-11e5-a74b-59530fbb6d8d\"" + i + "}";
channel.basicPublish("", "myQueue", null, message.getBytes("UTF-8"));
channel.close();
}

connection.close();
}

最佳答案

我做了一个简单的测试:

 final int perfFor = 100000;
d1 = new Date();
for (int i = 0; i < perfFor; i++) {
Channel channel1 = connection.createChannel();
channel1.close();

}
d2 = new Date();
seconds = (d2.getTime() - d1.getTime()) / 1000;
System.out.println("Seconds-Only-CreateDestroyChannels: " + seconds);


final AtomicInteger atomicInteger = new AtomicInteger();
ExecutorService threadChannels = Executors.newFixedThreadPool(1000);
final Date dThread = new Date();
for (int i = 0; i < perfFor; i++) {

threadChannels.submit(new Runnable() {
public void run() {
Channel channel1 = null;
try {
channel1 = connection.createChannel();
channel1.close();
if (atomicInteger.addAndGet(1) == perfFor) {
Date d2 = new Date();
long seconds = (d2.getTime() - dThread.getTime()) / 1000;
System.out.println("Seconds-Only-CreateDestroyChannels MultiThreads: " + seconds);
...

我得到了这个结果:

Seconds-Only-CreateDestroyChannels: 84
Seconds-Only-CreateDestroyChannels MultiThreads: 59

所以,我认为您不需要创建Channels池。您应该有一个线程 channel ,这意味着您启动线程并创建 channel

channel.exchangeDeclarechannel.queueDeclare 应该只调用一次,而不是每次发布都调用。

您还应该考虑增加Connection数量,单个Connection的1.000.000似乎有点不平衡。

我建议还阅读thisthis

RabbitMQ 有很多方法可以提高性能,您应该考虑您的所有环境,而不仅仅是 Channels

希望对你有帮助

关于java - 多线程环境中 RabbitMQ 的性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32789840/

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