RabbitMQ入门(三、RabbitMQ的Java使用)

这篇博客介绍了RabbitMQ的Java使用,从准备工作开始,包括简单队列、工作队列(轮询分发、公平分发)、订阅者模式(Fanout、Direct、Topic)。此外,还讲解了事务机制的Transaction模式和Confirm机制,提供了详细的代码示例和操作步骤,帮助读者深入理解RabbitMQ在实际应用中的用法。
摘要由CSDN通过智能技术生成

准备工作

首先需要安装配置好rabbitmq,网上很多教程,在此不再赘述。

创建用户hpsyche,密码:xxxxxx,同时创建host域(可以看做新建数据库),之后就可以进入代码阶段了(

首先导入包(此处创建的是maven工程)

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

新建一个utils工具类

package com.hpsyche.rabbitmq_learn.utils;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author fuzihao
 * @date 2019/8/23 16:52
 */
public class ConnectionUtils {
   
    private static class SingletonInstance{
   
        private static final ConnectionFactory factory=new ConnectionFactory();
    }

    private static ConnectionFactory getConncetionFactory(){
   
        return SingletonInstance.factory;
    }

    public static Connection getConnection() throws IOException, TimeoutException {
   
        ConnectionFactory factory=getConncetionFactory();
        factory.setUsername("hpsyche");
        factory.setPassword("XXXXXX");
        factory.setHost("127.0.0.1");
        factory.setVirtualHost("/vhost_test");
        factory.setPort(5672);
        return factory.newConnection();
    }
}

如果使用的是SpringBoot项目,注入bean

package com.hpsyche.rabbitmq_learn.utils;

import com.rabbitmq.client.ConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @author fuzihao
 * @date 2019/8/23 16:33
 */
@Component
public class GetRabbitConn {
   
    @Bean
    public ConnectionFactory getConnectionFactory(){
   
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setUsername("hpsyche");
        connectionFactory.setPassword("XXXXXX");
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setVirtualHost("/vhost_test");
        connectionFactory.setPort(5672);
        return connectionFactory;
    }
}

简单队列

首先是生产者

package com.hpsyche.rabbitmq_learn.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author fuzihao
 * @date 2019/8/26 11:39
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Producer {
   
    private static final String QUEUE_NAME="test_simple_queue";

    @Autowired
    private ConnectionFactory connectionFactory;

    @Test
    public void SimpleQueue() throws IOException, TimeoutException {
   
        //获得连接
        Connection connection = connectionFactory.newConnection();
        //获得信道
        Channel channel = connection.createChannel();
        //创建队列声明
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        //发送消息
        String msg="hello queue";
        channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());
        System.out.println("send msg");
        //关闭连接
        channel.close();
        connection.clearBlockedListeners();
    }
}

消费者

package com.hpsyche.rabbitmq_learn.simple;

import com.rabbitmq.client.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author fuzihao
 * @date 2019/8/26 11:40
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Receive {
   
    private static final String QUEUE_NAME="test_simple_queue";

    @Autowired
    private ConnectionFactory connectionFactory;

    @Test
    public void SimpleQueue() throws IOException, TimeoutException {
   
        //获得连接
        Connection connection = connectionFactory.newConnection();
        //获得信道
        Channel channel = connection.createChannel();
        //创建队列声明
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        //定义消费者
        Consumer consumer=new DefaultConsumer(channel){
   
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
   
                String msg=new String(body, StandardCharsets.UTF_8);
                System.out.println(msg);
            }
        };
        channel.basicConsume(QUEUE_NAME,true,consumer);
    }
}

首先启动生产者类,访问http://localhost:15672/#/queues
在这里插入图片描述
可以看到,该队列里已经有一个“准备好未消费”的消息了。

此时启动消费者类,再次查看,发现消息已经被消费了,total再次清为0;

但此时怎么查看之前消息的历史呢,此时我们需要引入rabbitmq的消息体日志信息的插件

  • 安装rabbitmq_tracing 插件,进入mq安装目录的sbin目录,执行rabbitmq-plugins enable rabbitmq_tracing

  • 使用MQ的web监控工具添加一个log trace

  • 在这里插入图片描述
    此时trace开始监控消息,再次启动生产者(两次),启动消费者,点击trace中的日志文件,查看日志:
    在这里插入图片描述
    可以看到消息产生及消费的信息
    在这里插入图片描述

工作队列

轮询分发

首先是生产者

package com.hpsyche.rabbitmq_learn.round;

import com.hpsyche.rabbitmq_learn.utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author fuzihao
 * @date 2019/8/26 12:47
 */
public class Producer {
   
    private static final String QUEUE_NAME="test_work_round_queue";

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
   
        //获得连接
        Connection connection = ConnectionUtils.getConnection();
        //获得信道
        Channel channel = connection.createChannel();
        //创建队列生命
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        //发送消息

        for(int i=0;i<50;i++){
   
            String msg="hello "+i;
            channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());
            System.out.println("send msg "+i);
            Thread.sleep(10);
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值