我正在创建一个REST api来向RabbitMQ发送消息,并试图了解创建/关闭频道的最佳做法。我正在使用RabbitMQ Java客户端API。
目前我有一个类RabbitMQPublisherConnection
,我在那里注入RabbitMQ连接。然后将该类弹簧注入另一个类RabbitMQPublisherChannel
。该类具有以下创建通道的功能:
public class RabbitMQPublisherChannel { public Channel createChannel(String amqpExchange, String exchangeType, String queue, String routingKey, boolean durableExchange, boolean durableQueue, boolean autoDelete, com.rabbitmq.client.Connection connection) throws IOException { Channel channel = null; channel = connection.createChannel(); if ((amqpExchange != null) && !"".equals(amqpExchange.trim())) { if (log.isLoggable(Level.FINEST)) { log.finest("exchange:" + amqpExchange + ", type: " + exchangeType + ", durableExchange: " + durableExchange); } channel.exchangeDeclare(amqpExchange, exchangeType, durableExchange); channel.queueDeclare(queue, durableQueue, false, autoDelete, null); channel.queueBind(queue, amqpExchange, routingKey); } return channel; } }
现在我有了第三课RabbitMQPublisher
,我在那里注入RabbitMQPublisherChannel
课程。我的应用程序上下文如下所示:
<bean id="rabbitMQPublisher" class="com.rabbitmq.RabbitMQPublisher">
<property name="publisherChannel" ref="rabbitMQPublisherChannel"/>
</bean>
<bean id="rabbitMQPublisherChannel" class="com.rabbitmq.RabbitMQPublisherChannel">
<property name="publisherConnection" ref="rabbitMQPublisherConnection"/>
</bean>
<bean id="rabbitMQPublisherConnection" class="com.rabbitmq.RabbitMQPublisherConnection">
<property name="rabbitMQConnectionSettingMap">
.. connection ..
</property>
</bean>
类RabbitMQPublisher
具有向RabbitMQ发布消息的功能:
public boolean publishMessage(String message, String queueName){
try {
// Validate queue name
com.rabbitmq.client.Channel channel = publisherChannel.getRabbitMQChannel(queueName);
RabbitMQConnection settings = publisherChannel.getPublisherConnection().getRabbitMQConnectionSettingMap().get(queueName);
if (channel != null) {
channel.basicPublish(settings.getAmqpExchange(), settings.getAmqpRoutingKey(), null, message.getBytes());
publisherChannel.closeChannel(channel);
}
} catch (AlreadyClosedException e) {
return FAILURE_RESPONSE;
} catch (IOException e) {
return FAILURE_RESPONSE;
}
return SUCCESS_RESPONSE;
}
这个应用程序是通过tomcat运行的,我注意到AppDynamics关闭通道需要花费47%的时间来发布消息。当我删除关闭通道的调用时,我将这47%的时间保存为32ms,但后来我在RabbitMQ管理控制台中注意到该连接的通道数量不断增加。
所以我的问题是 -
Even so, applications should prefer using a Channel per thread instead of sharing the same Channel across multiple threads.
)这是否意味着为每个线程创建一个新通道?由于
答案 0 :(得分:2)
由于您是Spring Framework用户,请考虑使用Spring AMQP。 RabbitTemplate
使用单个连接上的缓存通道,并为每个操作检出缓存(并返回)通道。默认缓存大小为1,因此通常需要为您的环境配置。