Springboot整合RabbitMQ简单案例

2022年11月24日 46点热度 0人点赞 0条评论

1. pom.xml引入jar包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2. 配置application.yml

根据自己的配置填写即可

spring:
  rabbitmq:
    username: xxx
    password: xxx
    virtual-host: /
    host: xxx
    port: 5672

3. 定义队列、定义交换机和绑定

发送消息之前需要创建交换机和队列,并完成绑定,否则会发送失败

有多种方式:

  1. RabbitMQ Management控制台手动创建
  2. 配置类定义方式
    @Configuration
    public class DirectRabbitMqConfiguration {
    
        //1.声明注册fanout模式的交换机
        @Bean
        public DirectExchange directExchange() {
            return new DirectExchange("direct_exchange", true, false);
        }
        //2.声明队列
        @Bean
        public Queue directSmsQueue(){
            return new Queue("sms.direct.queue",true);
        }
        //3.完成绑定关系
        @Bean
        public Binding directSmsBind() {
            return BindingBuilder.bind(directSmsQueue()).to(directExchange()).with("sms");
        }
    }
    
  3. 注解配置方式(在消费者中定义)
    import org.springframework.amqp.rabbit.annotation.RabbitHandler;
    import org.springframework.amqp.rabbit.annotation.RabbitListener;
    import org.springframework.stereotype.Component;
    
    @Component
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "sms.direct.queue",durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = "direct_exchange",type = ExchangeTypes.DIRECT),
            key = "#.email.#"
    ))
    public class Consumer {
    
        @RabbitHandler
        public void reviceMessage(String message) {
            System.out.println("接收到的信息是:"+message);
        }
    }
    

4. 生产者(发送消息)

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Component
public class OrderService {
        @Autowired
    private RabbitTemplate rabbitTemplate;

        public void sendMessage() {
        // 交换机名称
        String exchangeName = "direct_exchange";
        // 路由或者队列名称
        String routingKey = "sms";
        // 消息内容
        String message = "";
        rabbitTemplate.convertAndSend(exchangeName,routingKey,message);
    }
}

5. 消费者(接收消息)

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;

@Component
public class Consumer {

    @RabbitHandler
    @RabbitListener(queues = {"sms.direct.queue"})
    public void reviceMessage(String message, Channel channel, Message messages, @Headers Map<String,Object> headers) {
        System.out.println("接收到的信息是:"+message);
    }
}

王谷雨

一个苟且偷生的java程序员

文章评论