[英]create queue/exchange/binding/listener at run time in spring boot rabbitmq
我在rabbitmq中使用spring-boot。 我創建了一些固定的隊列/交換/綁定/偵聽器。
偵聽器的創建如下:
@RabbitListener
public void foo(String msg) {...}
現在,我想在運行時為每個用戶在與交換/綁定/偵聽器一起登錄時創建隊列,並在用戶注銷時銷毀這些隊列。 我如何在春季啟動中做到這一點。
您無法使用@RabbitListener
輕松完成此@RabbitListener
(可以,但是必須為每個應用程序創建一個新的子應用程序上下文)。
您可以使用RabbitAdmin
動態創建隊列和綁定,並為每個新隊列創建消息偵聽器容器。
編輯
這是使用@RabbitListener
和子上下文的一種方法。 使用Spring Boot時, ListenerConfig
類不得與引導應用程序本身位於同一軟件包(或子軟件包)中。
@SpringBootApplication
public class So48617898Application {
public static void main(String[] args) {
SpringApplication.run(So48617898Application.class, args).close();
}
private final Map<String, ConfigurableApplicationContext> children = new HashMap<>();
@Bean
public ApplicationRunner runner(RabbitTemplate template, ApplicationContext context) {
return args -> {
Scanner scanner = new Scanner(System.in);
String line = null;
while (true) {
System.out.println("Enter a new queue");
line = scanner.next();
if ("quit".equals(line)) {
break;
}
children.put(line, addNewListener(line, context));
template.convertAndSend(line, "test to " + line);
}
scanner.close();
for (ConfigurableApplicationContext ctx : this.children.values()) {
ctx.stop();
}
};
}
private ConfigurableApplicationContext addNewListener(String queue, ApplicationContext context) {
AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext();
child.setParent(context);
ConfigurableEnvironment environment = child.getEnvironment();
Properties properties = new Properties();
properties.setProperty("queue.name", queue);
PropertiesPropertySource pps = new PropertiesPropertySource("props", properties);
environment.getPropertySources().addLast(pps);
child.register(ListenerConfig.class);
child.refresh();
return child;
}
}
和
@Configuration
@EnableRabbit
public class ListenerConfig {
@RabbitListener(queues = "${queue.name}")
public void listen(String in, @Header(AmqpHeaders.CONSUMER_QUEUE) String queue) {
System.out.println("Received " + in + " from queue " + queue);
}
@Bean
public Queue queue(@Value("${queue.name}") String name) {
return new Queue(name);
}
@Bean
public RabbitAdmin admin(ConnectionFactory cf) {
return new RabbitAdmin(cf);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.