Springboot結合rabbitmq

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/>
    </parent>
    <!--爲了打包-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

    </dependencies>

生產者代碼,主題交換機

主題交換機的routKey是有通配符*和#的。

*代表必有一單詞,#代表0或多個單詞

單獨#代表必發

@Configuration
public class RabbitConfig {

    @Bean
    TopicExchange myTopicExchange(){
        return new TopicExchange("myTopicExchange");
    }

    @Bean
    Queue myque1(){
        return new Queue("myque1");
    }
    @Bean
    Queue myque2(){
        return new Queue("myque2");
    }
    @Bean
    Queue myque3(){
        return new Queue("myque3");
    }
    @Bean
    Queue myque4(){
        return new Queue("myque4");
    }

    @Bean
    Binding b1(){
        return BindingBuilder.bind(myque1()).to(myTopicExchange()).with("#");
    }
    @Bean
    Binding b2(){
        return BindingBuilder.bind(myque2()).to(myTopicExchange()).with("myque.111");
    }
    @Bean
    Binding b3(){
        return BindingBuilder.bind(myque3()).to(myTopicExchange()).with("myque.*");
    }
    @Bean
    Binding b4(){
        return BindingBuilder.bind(myque4()).to(myTopicExchange()).with("myque.#");
    }
}
@Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {

       // rabbitTemplate.convertAndSend("myTopicExchange","my","222");
        rabbitTemplate.convertAndSend("myTopicExchange","myque.111","222");
         rabbitTemplate.convertAndSend("myTopicExchange","myque.111.222","222");
    }

 

 

 

消費者,可以放到一個另一個項目裏面

 

@Service
public class DirectReceiver {

    @RabbitHandler
    @RabbitListener(queues = "myque1")
    public void process1(String testMessage) {
        System.out.println("myque1消費者收到消息  : " + testMessage.toString());
    }

    @RabbitHandler
    @RabbitListener(queues = "myque2")
    public void process2(String testMessage) {
        System.out.println("myque2消費者收到消息  : " + testMessage.toString());
    }

    @RabbitHandler
    @RabbitListener(queues = "myque3")
    public void process3(String testMessage) {
        System.out.println("myque3消費者收到消息  : " + testMessage.toString());
    }

    @RabbitHandler
    @RabbitListener(queues = "myque4")
    public void process4(String testMessage) {
        System.out.println("myque4消費者收到消息  : " + testMessage.toString());
    }
}

 

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