我现在正在处理一个使用rabbitmq、Spring和Hibernate的项目,一旦我的程序开始运行,用户就可以更改数据库中的布尔值字段。
如果为真,我的程序将创建一个新的队列,并将一个预定的交换绑定到它。
如果为false,我的程序将解除绑定队列并删除它。
然而,我看过的所有教程似乎都是在程序首次运行时使用注释来创建队列和绑定:
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Profile({"tut3", "pub-sub", "publish-subscribe"})
@Configuration
public class Tut3Config {
@Bean
public FanoutExchange fanout() {
return new FanoutExchange("tut.fanout");
}
@Profile("receiver")
private static class ReceiverConfig {
@Bean
public Queue autoDeleteQueue1() {
return new AnonymousQueue();
}
@Bean
public Queue autoDeleteQueue2() {
return new AnonymousQueue();
}
@Bean
public Binding binding1(FanoutExchange fanout,
Queue autoDeleteQueue1) {
return BindingBuilder.bind(autoDeleteQueue1).to(fanout);
}
@Bean
public Binding binding2(FanoutExchange fanout,
Queue autoDeleteQueue2) {
return BindingBuilder.bind(autoDeleteQueue2).to(fanout);
}
@Bean
public Tut3Receiver receiver() {
return new Tut3Receiver();
}
}
@Profile("sender")
@Bean
public Tut3Sender sender() {
return new Tut3Sender();
}
}在我的例子中,我是否应该实现诸如AmqpAdmin之类的接口并显式地使用诸如declareQueue()和deleteQueue之类的方法来能够不断地创建和删除队列,而不是使用注释?
如果是这样的话,Spring是否在项目中有特定的位置来实现这些方法?
谢谢。
发布于 2017-06-11 19:02:32
在您的示例中,队列bean autoDeleteQueue1和autoDeleteQueue1是使用scope singleton创建的,因此它们在整个应用程序生命周期中都存在于容器中。
如果您需要更灵活的方法来处理队列bean,您可以使用AmqpAdmin的默认实现,如下所述。
if (condition) {
Queue queue = admin.declareQueue(new Queue("queueOne"));
admin.declareBinding(new Binding(queue, fanout))
} else {
admin.removeBindings(new Binding(new Queue("queueOne"), fanout))
}您可能希望将此代码放入某个服务或任何处理此逻辑的类中。在该服务中,您可以连接bean
@Bean
public ConnectionFactory connectionFactory() {
return new CachingConnectionFactory();
}
@Bean
public AmqpAdmin admin() {
return new RabbitAdmin(connectionFactory());
}
@Bean
public FanoutExchange fanout() {
return new FanoutExchange("tut.fanout");
}更多详情请访问:here
发布于 2017-06-13 00:49:54
如果您查看使用Java的RabbitMQ教程,您会发现#2和#5教程适用于您的情况。
例如,要创建一个队列,您可以使用以下命令:
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);要创建绑定,您可以执行以下操作:
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "topic");
String queueName = channel.queueDeclare().getQueue();
if (argv.length < 1) {
System.err.println("Usage: ReceiveLogsTopic [binding_key]...");
System.exit(1);
}
for (String bindingKey : argv) {
channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);
}对于您的情况,基本上您希望显式地创建通道并显式地创建/绑定,而不是通过bean。
这些操作中的每一个都可以是收集在服务类中的自己的方法。
然后,您可以简单地利用服务类来使用每个方法。通过这种方式,您可以随时创建/绑定。
https://stackoverflow.com/questions/44333311
复制相似问题