Spring AMQP 中CachingConnectionFactory的生产者消费者分离

论坛 期权论坛 脚本     
匿名技术用户   2021-1-9 02:02   128   0

Spring AMQP 中CachingConnectionFactory应该配置几个?

摘自官方:

When the application is configured with a single CachingConnectionFactory, as it is by default with Spring Boot auto-configuration, the application stops working when the connection is blocked by the Broker. And when it is blocked by the Broker, any of its clients stop to work. If we have producers and consumers in the same application, we may end up with a deadlock when producers are blocking the connection (because there are no resources on the Broker any more) and consumers cannot free them (because the connection is blocked). To mitigate the problem, we suggest having one more separate CachingConnectionFactory instance with the same options—one for producers and one for consumers. A separate CachingConnectionFactory is not possible for transactional producers that execute on a consumer thread, since they should reuse the Channel associated with the consumer transactions.

当应用程序配置为单个CachingConnectionFactory时(springboot默认自动配置),一旦连接在broker发生阻塞,应用程序会停止工作。当这种情况发生时,所有client都会停止工作。如果生产者和消费者在同一个应用中,当一个生产者被broker阻塞,而消费者又无法释放生产者,会导致死锁。

为了缓解这个问题,建议再创建一个具有相同的配置的单独的CachingConnectionFactory实例,一个用于生产者,一个用于消费者。这样,即使生产者链接发生阻塞,不会影响消费者的链接。

如何使用隔离的connection

2.0.2以后,事务型的RabbitTemplate提供了一个配置属性usePublisherConnection可以支持自动使用第二个connection factory,可以将usePublisherConnection属性设置为true 来使用一个不同的链接,这样可以避免一个producer阻塞不会影响其他consumers,CachingConnectionFactory 现在可以维持另一个内部connection factory。

rabbitTemplate.setUsePublisherConnection(true);

如果rabbit template在listener container开启的一个事务中运行,会忽略这个属性直接使用container的channel。

注意:不要在RabbitAdmin 中使用usePublisherConnection 设置为true的rabbit template。因为RabbitAdmin通常被用来为listener containers声明队列,当使用usePublisherConnection 为true的rabbit template声明队列时,队列会声明为一个排他的队列(例如匿名队列AnonymousQueue),由于使用的不同的链接,队列将不能被containers使用。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP