SpringBoot简单整合RabbitMQ

目录

原生RabbitMQ(maven)生产者

原生RabbitMQ(maven)消费者

springboot整合producer生产者

springboot整合consumer消费者


原生RabbitMQ(maven)生产者

1.创建maven项目producer,并导入依赖

<dependencies>
        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>5.6.0</version>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

 2.创建producer类,这里举例简单工作模式

public class producer_helloWorld {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2.设置参数
        factory.setHost("192.168.5.129"); //ip
        factory.setPort(5672);            //rabbitmq端口号默认5672
        factory.setVirtualHost("/");      //虚拟机名称
        factory.setUsername("guest");        
        factory.setPassword("guest");
        //3.创建连接Connection
        Connection connection = factory.newConnection();
        //4.创建Channel
        Channel channel = connection.createChannel();
        //5.创建队列Queue
        /*
        queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
        参数:
            1. queue:队列名称
            2. durable:是否持久化,当mq重启之后,还在
            3. exclusive:
                * 是否独占。只能有一个消费者监听这队列
                * 当Connection关闭时,是否删除队列
                *
            4. autoDelete:是否自动删除。当没有Consumer时,自动删除掉
            5. arguments:参数。

         */
        //如果没有一个名字叫hello_world的队列,则会创建该队列,如果有则不会创建
        channel.queueDeclare("hello_rabbitmq",true,false,false,null);

        String body="hello rabbitmq~~~";
        //6.发送消息
        /*
        basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)
        参数:
            1. exchange:交换机名称。简单模式下交换机会使用默认的 ""
            2. routingKey:路由名称
            3. props:配置信息
            4. body:发送消息数据

         */
        channel.basicPublish("","hello_rabbitmq",null,body.getBytes());
        //7.释放资源
        channel.close();
        connection.close();
    }
}

原生RabbitMQ(maven)消费者

1.创建maven项目consumer,并导入依赖,跟producer依赖一致

2.创建consumer类

public class consumer_helloWorld {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2.设置参数
        factory.setHost("192.168.5.129");
        factory.setPort(5672);
        factory.setVirtualHost("/");
        factory.setUsername("guest");
        factory.setPassword("guest");
        //3.创建连接Connection
        Connection connection = factory.newConnection();
        //4.创建Channel
        Channel channel = connection.createChannel();
        //5.创建队列Queue
        /*queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
        参数:
        1. queue:队列名称
        2. durable:是否持久化,当mq重启之后,还在
        3. exclusive:
                * 是否独占。只能有一个消费者监听这队列
                * 当Connection关闭时,是否删除队列
                *
                4. autoDelete:是否自动删除。当没有Consumer时,自动删除掉
        5. arguments:参数。

         */
        channel.queueDeclare("hello_rabbitmq",true,false,false,null);
        //6.接收消息
        Consumer consumer = new DefaultConsumer(channel){
            /*
            回调方法,当收到消息后,会自动执行该方法
                1. consumerTag:标识
                2. envelope:获取一些信息,交换机,路由key...
                    3. properties:配置信息
                4. body:数据
             */
            @Override
            public void handleDelivery(java.lang.String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("----------------------------");
                System.out.println("body:"+new String(body));
                System.out.println("----------------------------");
            }
        };
        channel.basicConsume("hello_rabbitmq",true,consumer);
    }
}

先启动生产者工程,在启动消费者工程,查看控制台即可 

切记:这里consumer服务不必关闭,消费者需等待队列消息

springboot整合producer生产者

1.创建生产者springboot工程,引入RabbitMQ服务,可以命名为springboot-producer为生产者

 2.引入junit单元测试,本次在单元测试中

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <scope>test</scope>
</dependency>

3.编写yml配置信息 

spring:
  rabbitmq:
    host: 192.168.5.129 #ip
    port: 5672					#端口号
    username: guest				
    password: guest
    virtual-host: /			#虚拟机名称

切记:5672不是15672

4.定义交换机,队列以及绑定关系的配置类,这里测试的是Topics通配符模式

@Configuration
public class RabbitMQConfig {

    public static final String EXCHANGE_NAME="boot_topic_exchange";
    public static final String QUEUE_NAME="boot_queue";

    //1.交换机
    @Bean("bootExchange")
    public Exchange bootExchange(){

        //durable:是否持久化
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }
    //2.Queue队列
    @Bean("bootQueue")
    public Queue bootQueue(){
        return QueueBuilder.durable(QUEUE_NAME).build();
    }

    //3.队列和交换机绑定关系 Binding
    /*
    * 1.直到哪个队列
    * 2.知道哪个交换机
    * 3.routing key
    * */

    @Bean
    public Binding bindQueueExchange(@Qualifier("bootQueue")Queue queue,@Qualifier("bootExchange") Exchange exchange){
        System.out.println(123);
        return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
    }
}

切记:将config包放置在在springboot启动类同类包或子类包中,否则springboot将不能扫描到@Configuartion注解,将无法通过@Bean创建队列,更无法发送消息

5.使用测试类注入RabbitTemplate,调用方法,完成消息发送的测试

@SpringBootTest
@RunWith(SpringRunner.class)
class SpringbootRabbitmqApplicationTests {

    //1.注入RabbitTemplate
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Test
    void testSend() {
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.haha","boot mq hello~~~");
    }

}

springboot整合consumer消费者

1.创建生产者springboot工程,引入RabbitMQ服务,可以命名为springboot-consumer为消费者2.

2.编写yml配置文件 

spring:
  rabbitmq:
    host: 192.168.5.129 #ip
    port: 5672
    username: guest
    password: guest
    virtual-host: /

3.定义监听类,使用@RabbitListener注解完成队列监听 

@Component
public class RabbitMQListener {
    @RabbitListener(queues = "boot_queue")
    public void ListenerQueue(Message message){
        System.out.println(new String(message.getBody()));
    }
}

切记:RabbitMQListener类创建在springboot启动类的同类包或者子类包中,否则springboot将无法扫描到

最后启动生产者,然后启动消费者,即可读取到消息

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值