Spring Boot 整合 RabbitMQ(二)

  • 新建生产者工程

maven 依赖,方便测试引入测试包

    
        
            org.springframework.boot
            spring-boot-starter-amqp
        
        
            org.springframework.boot
            spring-boot-starter-test
        
    

配置文件yml

spring:
  rabbitmq:
      host: localhost
      port: 5672
      virtual-host: itea
      username: dxayga
      password: dxayga

Spring 配置类以 topic模式为例:

@Configuration
public class RabbitMQConfig {

    //交换机名称
    public final static String ITEM_TOPIC_EXCHANGE = "item_topic_exchange";
    //队列名称
    public final static String ITEM_QUEUE = "item_queue";

    /**
     * 声明交换机
     * 注意ExchangeBuilder有三个方法
     * @return
     */
    @Bean
    public Exchange exchange(){
        return ExchangeBuilder.topicExchange(ITEM_TOPIC_EXCHANGE).durable(true).autoDelete().build();
    }

    /**
     * 声明队列
     * @return
     */
    @Bean
    public Queue queue(){
        return QueueBuilder.durable(ITEM_QUEUE).build();
    }

    /**
     * 绑定到交换机
     * @return
     */
    @Bean
    public Binding binding(){
        return BindingBuilder.bind(queue()).to(exchange()).with("item.#").noargs();
    }

}

写一个测试类发送消息

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ProviderApplication.class)
public class RabbitMQTest {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void test(){
        System.out.println(rabbitTemplate);
        rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE,
                "item.insert","这是一个测试消息,Routing is item.insert") ;
        rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE,
                "item.update","这是一个测试消息,Routing is item.update");
        rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE,
                "item.delete","这是一个测试消息,Routing is item.delete");
        System.out.println("消息发送");
    }

}
  • 新建消费者工程(pom和yml和生产者工程相同)

在消费者工程只要写一个监听类

@Component
public class RabbitMQListener {

    @RabbitListener(queues = "item_queue")
    public void listener(String message){
        System.out.println("接收到的消息:"+message);
    }

}

测试结果:

2020-08-16 17:46:16.979  INFO 10112 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
2020-08-16 17:51:16.981  INFO 10112 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
接收到的消息:这是一个测试消息,Routing is item.insert
接收到的消息:这是一个测试消息,Routing is item.update
接收到的消息:这是一个测试消息,Routing is item.delete

 

你可能感兴趣的:(消息中间件,j2ee)