rabbitmq 交換模式-Topic

這裏寫圖片描述

java 核心代碼

import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

public class Topic {
    public static void main(String[] args) throws InterruptedException {
        CachingConnectionFactory cf = new CachingConnectionFactory("ip");
        cf.setUsername("root");
        cf.setPassword("");


        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.*"));
        RabbitTemplate template = new RabbitTemplate(cf);
        template.convertAndSend("myExchange", "foo.bar", "Hello, world!");
    }
}

綁定後效果如下:

這裏寫圖片描述

使用 spring 配置
使用 spring-rabbit
topic 模式中的,需要指定過濾模式

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
    http://www.springframework.org/schema/rabbit
    http://www.springframework.org/schema/rabbit/spring-rabbit-1.7.xsd">
<!-- 連接配置 -->
    <rabbit:connection-factory id="connectionFactory"
        host="ip" username="root" password="" />
    <rabbit:admin connection-factory="connectionFactory" />

    <!-- spring rabbit template聲明 -->
    <rabbit:template exchange="xxx" id="amqpTemplate"
        connection-factory="connectionFactory" />


    <rabbit:queue name="test_queue_key"></rabbit:queue>

    <rabbit:queue name="test2"></rabbit:queue>
  <!--交換聲明-->
    <rabbit:topic-exchange name="xxx">
        <rabbit:bindings>
            <rabbit:binding queue="test_queue_key" pattern="foo.*"></rabbit:binding>

        </rabbit:bindings>

    </rabbit:topic-exchange>
    <beans>

代碼:

AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("rabbit.xml");
        RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
        template.convertAndSend("foo.df", "hello");

        Thread.sleep(1000);
        ctx.destroy();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章