【RabbitMQ】——Spring AMQP
程序员文章站
2022-07-12 12:32:05
...
本博文首先让大家对Spring AMQP有个初步认识。接下来的系列博客中,会对其逐步深入。
目前国内大部分软件行业都在使用Spring平台框架,在Spring AMQP中包括两大部分:spring-amqp 和spring-rabbit。
spring-amqp是对高级消息队列协议(amqp)的支持和抽象
spring-rabbit是Spring集成的 对MQ的 实现:Spring选择的是RabbitMQ。RabbitMQ是基于amqp实现的。——从Spring的选择来看,RabbitMQ在国内是处于举足轻重的地位。
Spring AMQP特性:
1、用于异步处理入站邮件的侦听器容器
2、RabbitTemplate发送和接收消息
3、RabbitAdmin用于自动声明队列,交换和绑定
快速起步,看效果,填满自信感~~
在项目中使用spring-amqp,Spring官网推荐使用依赖关系管理系统,如:maven
则可以将如下代码贴到pom文件中
<dependencies>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.7.3.RELEASE</version>
</dependency>
</dependencies>
如果单纯java代码实现,如下:
public static void main(final String... args) throws Exception {
ConnectionFactory cf = new CachingConnectionFactory();
// set up the queue, exchange, binding on the broker
RabbitAdmin admin = new RabbitAdmin(cf);
Queue queue = new Queue("myQueue");
admin.declareQueue(queue);
TopicExchange exchange = new TopicExchange("myExchange");
admin.declareExchange(exchange);
admin.declareBinding(
BindingBuilder.bind(queue).to(exchange).with("foo.*"));
// set up the listener and container
SimpleMessageListenerContainer container =
new SimpleMessageListenerContainer(cf);
Object listener = new Object() {
public void handleMessage(String foo) {
System.out.println(foo);
}
};
MessageListenerAdapter adapter = new MessageListenerAdapter(listener);
container.setMessageListener(adapter);
container.setQueueNames("myQueue");
container.start();
// send something
RabbitTemplate template = new RabbitTemplate(cf);
template.convertAndSend("myExchange", "foo.bar", "Hello, world!");
Thread.sleep(1000);
container.stop();
}
如果在Spring中应用:
public static void main(final String... args) throws Exception {
AbstractApplicationContext ctx =
new ClassPathXmlApplicationContext("context.xml");
RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
template.convertAndSend("Hello, world!");
Thread.sleep(1000);
ctx.destroy();
}
public class Foo {
public void listen(String foo) {
System.out.println(foo);
}
}
<rabbit:connection-factory id="connectionFactory" />
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory"
exchange="myExchange" routing-key="foo.bar"/>
<rabbit:admin connection-factory="connectionFactory" />
<rabbit:queue name="myQueue" />
<rabbit:topic-exchange name="myExchange">
<rabbit:bindings>
<rabbit:binding queue="myQueue" pattern="foo.*" />
</rabbit:bindings>
</rabbit:topic-exchange>
<rabbit:listener-container connection-factory="connectionFactory">
<rabbit:listener ref="foo" method="listen" queue-names="myQueue" />
</rabbit:listener-container>
<bean id="foo" class="foo.Foo" />