spring封装的RabbitMQ

  spring这么牛逼的团队,封装了RabbitMQ,简化了RabbitMQ的使用,那肯定是要使用spring-rabbit了

一、简介

二、使用方法

1、消费者

1 public class Foo {
2 
3     //具体执行业务的方法
4     public void listen(String foo) {
5         System.out.println("消费者: " + foo);
6     }
7 }

2、生产者

public class SpringMain {
    
    public static void main(final String... args) throws Exception {
        AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(
                "classpath:spring/rabbitmq-context.xml");
        //RabbitMQ模板
        RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
        //发送消息
        template.convertAndSend("Hello, world!");
        Thread.sleep(1000);// 休眠1秒
        ctx.destroy(); //容器销毁
    }
}

注意:这个好像是前面的类似创建交换机、创建队列、以及交换机和队列的绑定,似乎都没有看到,不是不见了,而是都放到配置文件中去了

3、配置文件

3.1 定义连接工厂

1     <!-- 定义RabbitMQ的连接工厂 -->
2     <rabbit:connection-factory id="connectionFactory"
3         host="127.0.0.1" port="5672" username="taotao" password="taotao"
4         virtual-host="/taotao" />

3.2 定义模板(可以指定交换机或队列)

1     <!-- 定义Rabbit模板,指定连接工厂以及定义exchange -->
2     <rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="fanoutExchange" />

3.3 定义队列、交换机、以及完成队列和交换机的绑定

1     <!-- 定义队列,自动声明 -->
2     <rabbit:queue name="myQueue" auto-declare="true" durable="false"/>
3     
4     <!-- 定义交换器,自动声明 -->
5     <rabbit:fanout-exchange name="fanoutExchange" auto-declare="true" durable="false">
6         <rabbit:bindings>
7             <rabbit:binding queue="myQueue"/>
8         </rabbit:bindings>
9     </rabbit:fanout-exchange>

3.4 定义监听

1     <!-- 队列监听 -->
2     <rabbit:listener-container connection-factory="connectionFactory">
3         <rabbit:listener ref="foo" method="listen" queue-names="myQueue" />
4     </rabbit:listener-container>
5 
6     <bean id="foo" class="cn.itcast.rabbitmq.spring.Foo" />

3.5 定义管理,用于管理队列、交换机等

1     <!-- MQ的管理,包括队列、交换器等 -->
2     <rabbit:admin connection-factory="connectionFactory" />

三、持久化交换机和队列

持久化:将交换机或队列的数据保存到磁盘,服务器宕机或重启之后依然存在。

非持久化:将交换机或队列的数据保存到内存,服务器宕机或重启之后将不存在。

非持久化的性能高于持久化。

如何选择持久化?非持久化?  --看需求。

原文地址:https://www.cnblogs.com/ssh-html/p/10548099.html