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>

配置文件yml

spring:
  #给项目来个名字
  application:
    name: rabbitmq-provider
  #配置rabbitMq 服务器
  rabbitmq:
    host: 192.168.0.10
    port: 5672
    username: guest
    password: guest

生产者代码,主题交换机

主题交换机的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());
    }
}

猜你喜欢

转载自blog.csdn.net/dmw412724/article/details/106238156