我想使用特定模式的队列名称,例如 project.{queue-name}.queue
.为了保持这种模式稳固,我编写了一个辅助类来从一个简单的标识符生成这个名称。所以,foo
将生成一个名为 project.foo.queue
的队列.简单的。
但是,注释RabbitListener
需要一个常量字符串,并使用我的助手类给我一个错误。我如何使用 RabbitListener
实现这一点(或者可能是另一种方法)注解?
@Component
public class FooListener {
// it doesn't work
@RabbitListener(queues = QueueName.for("foo"))
// it works
@RabbitListener(queues = "project.foo.queue")
void receive(final FooMessage message) {
// ...
}
}
最佳答案
要创建和监听从动态 UUID 构造的队列名称,您可以使用 random.uuid .
问题是这必须只在一个地方被捕获到一个 Java 变量中,因为 a new random value would be generated each time the property is referenced .
解决方法是使用Spring Expression Language (SpEL)调用提供配置值的函数,例如:
@RabbitListener(queues = "#{configureAMQP.getControlQueueName()}")
void receive(final FooMessage message) {
// ...
}
使用以下内容创建队列:
@Configuration
public class ConfigureAMQP {
@Value("${controlQueuePrefix}-${random.uuid}")
private String controlQueueName;
public String getControlQueueName() {
return controlQueueName;
}
@Bean
public Queue controlQueue() {
System.out.println("controlQueue(): controlQueueName=" + controlQueueName);
return new Queue(controlQueueName, true, true, true);
}
}
请注意,SpEL 中使用的必要 bean 是基于
@Configuration
隐式创建的。类(拼写略有变化 ConfigureAMQP
-> configureAMQP
)。
关于java - RabbitListener 注释上的动态队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49909859/