RabbitMQ生产者与消费者练手小记

1.实现步骤

1.创建连接工厂
2.设置MQ相关信息
3.创建一个新的连接
4.创建一个通道
5.queueDeclare:声明一个队列(生产者声明,消费者关注)
6.basicPublish(将消息放入队列中)

7.关闭通道、关闭连接(生产者专属)

2.相关代码

1.生产者

package RabbitMQ;

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

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

/**
 * @author wzb
 * @date 2023/3/20  10:44
 */
public class Producer {
    public final static String QUEUE_NAME="rabbitMQ.test";
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory factory=new ConnectionFactory();
        //设置MQ相关信息
        factory.setHost("localhost");
        factory.setUsername("guest");
        factory.setPassword("guest");

        //创建一个新的连接
        Connection connection=factory.newConnection();
        //创建一个通道
        Channel channel=connection.createChannel();
        //声明一个队列
        //注1:queueDeclare第一个参数表示队列名称、第二个参数为是否持久化(true表示是,队列将在服务器重启时生存)、
        // 第三个参数为是否是独占队列(创建者可以使用的私有队列,断开后自动删除)、
        // 第四个参数为当所有消费者客户端连接断开时是否自动删除队列、第五个参数为队列的其他参数
        //channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        String message="Hello,RabbitMQ!";
        //发送DAO到消息队列中
        //注2:basicPublish第一个参数为交换机名称、第二个参数为队列映射的路由key、第三个参数为消息的其他属性、
        // 第四个参数为发送信息的主体
        channel.basicPublish("",QUEUE_NAME,null,message.getBytes("UTF-8"));
        System.out.println("Producer send '"+message+"'");
        //关闭通道
        channel.close();
        //关闭连接
        connection.close();
    }
}

2.消费者

package RabbitMQ;

import com.rabbitmq.client.*;

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

/**
 * @author wzb
 * @date 2023/3/20  11:00
 */
public class Customer {
    public final static String QUEUE_NAME="rabbitMQ.test";
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory factory=new ConnectionFactory();
        //设置MQ相关信息
        factory.setHost("localhost");
        factory.setUsername("guest");
        factory.setPassword("guest");
        //创建一个新的连接
        Connection connection = factory.newConnection();
        //创建一个通道
        Channel channel = connection.createChannel();
        //声明要关注的队列
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        System.out.println("Customer waiting received message!");
        //DefaultConsumer类实现了Consumer接口,通过传入一个频道,
        // 告诉服务器我们需要那个频道的消息,如果频道中有消息,就会执行回调函数handleDelivery
        Consumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message=new String(body,"UTF-8");
                System.out.println("Customer received '"+message+"'");
            }
        };

        //自动回复队列应答 -- RabbitMQ中的消息确认机制
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }
}

3.执行效果
在这里插入图片描述
在这里插入图片描述

小进阶:消息分发

1.生产者

package RabbitMQ;

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

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

/**
 * @author wzb
 * @date 2023/3/21  14:48
 */
public class NewTask {
    private static final String TASK_QUEUE_NAME="task_queue";
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection=factory.newConnection();
        Channel channel=connection.createChannel();
        channel.queueDeclare(TASK_QUEUE_NAME,true,false,false,null);
        for (int i = 0; i < 10; i++) {
            String message="hello rabbitMQ"+i;
            channel.basicPublish("",TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,message.getBytes());
            System.out.println("NewTask send '"+message+"'");
        }
        TimeUnit.SECONDS.sleep(10000000);
       channel.close();
       connection.close();
    }
}

2.消费者(可以创建多个消费者,代码一样)

package RabbitMQ;

import com.rabbitmq.client.*;

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

/**
 * @author wzb
 * @date 2023/3/21  15:48
 */
public class Work1 {
    private static final String TASK_QUEUE_NAME="task_queue";
    public static void main(String[] args) throws IOException, TimeoutException {
        final ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("localhost");
        final Connection connection=factory.newConnection();
        final Channel channel=connection.createChannel();
        channel.queueDeclare(TASK_QUEUE_NAME,true,false,false,null);
        System.out.println("Worker1  Waiting for messages");
        //每次从队列获取的数量
        channel.basicQos(1);

        final Consumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message=new String(body,"UTF-8");
                System.out.println("Worker1  Received '" + message + "'");
                System.out.println("Worker1 sleep!");
                doWork(message);
                channel.basicAck(envelope.getDeliveryTag(),false);

            }
        };

        boolean autoAck=false;
        //消息消费完成确认
        channel.basicConsume(TASK_QUEUE_NAME, autoAck, consumer);

    }
    private static void doWork(String task) {
        try {
            Thread.sleep(1000); // 暂停1秒钟
        } catch (InterruptedException _ignored) {
            Thread.currentThread().interrupt();
        }
    }
}

3.执行效果
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

发布/订阅

1.生产者

package RabbitMQ;

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

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

/**
 * @author wzb
 * @date 2023/3/23  10:42
 */
public class EmitLog {
    private final static  String EXCHANGE_NAME="logs";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection=factory.newConnection();
        Channel channel=connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME,"fanout");//fanout表示分发,所有的消费者都能得到相同的队列信息

        //分发消息
        for (int i = 0; i < 5; i++) {
            String message="I'M  "+i;
            channel.basicPublish(EXCHANGE_NAME,"",null,message.getBytes());
            System.out.println("The log send :"+message);
        }
        channel.close();
        connection.close();
    }
}

2.消费者

package RabbitMQ;

import com.rabbitmq.client.*;

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


/**
 * @author wzb
 * @date 2023/3/23  14:55
 */
public class ReceiveLog1 {
    private static final String EXCHANGE_NAME = "logs";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
        //产生一个随机的队列名称
        String queueName=channel.queueDeclare().getQueue();
        //将队列进行绑定
        channel.queueBind(queueName,EXCHANGE_NAME,"");
        System.out.println("Receive work1 waiting for message!");
        Consumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("ReceiveLogs1 Received '" + message + "'");

            }
        };
        channel.basicConsume(queueName, true, consumer);//队列会自动删除
    }


}

执行效果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Routing 采用路由的方式对不同的消息进行过滤

1.生产者

package RabbitMQ;

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

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

/**
 * @author wzb
 * @date 2023/3/24  10:26
 */
public class RoutingSendDirect {
    private static final String EXCHANGE_NAME = "direct_logs";
    // 路由关键字
    private static final String[] routingKeys = new String[]{"info" ,"warning", "error"};

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME,"direct");//注意是direct
        //发送信息
        for (String routingKey:routingKeys){
            String message = "RoutingSendDirect Send the message level:" + routingKey;
            channel.basicPublish(EXCHANGE_NAME,routingKey,null,message.getBytes());
            System.out.println("RoutingSendDirect Send"+routingKey +"':'" + message);
        }
        channel.close();
        connection.close();
    }
}

2.消费者1

package RabbitMQ;

import com.rabbitmq.client.*;

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

/**
 * @author wzb
 * @date 2023/3/24  14:16
 */
public class ReceiveLogsDirect1 {
    // 交换器名称
    private static final String EXCHANGE_NAME = "direct_logs";
    // 路由关键字
    private static final String[] routingKeys = new String[]{"info", "warning"};

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //声明交换器
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        //获取匿名队列名称
        String queueName = channel.queueDeclare().getQueue();

        //根据路由关键字进行绑定
        for (String routingKey : routingKeys) {
            channel.queueBind(queueName, EXCHANGE_NAME, routingKey);
            System.out.println("ReceiveLogsDirect1 exchange:" + EXCHANGE_NAME + "," +
                    " queue:" + queueName + ", BindRoutingKey:" + routingKey);
        }
        System.out.println("ReceiveLogsDirect1  Waiting for messages");
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("ReceiveLogsDirect1 Received '" + envelope.getRoutingKey() + "':'" + message + "'");
            }
        };
        channel.basicConsume(queueName, true, consumer);
    }
}

3.消费者2

package RabbitMQ;

import com.rabbitmq.client.*;


import java.io.UnsupportedEncodingException;


/**
 * @author wzb
 * @date 2023/3/24  14:16
 */
public class ReceiveLogsDirect2 {
    // 交换器名称
    private static final String EXCHANGE_NAME = "direct_logs";
    // 路由关键字
    private static final String[] routingKeys = new String[]{"error"};

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //声明交换器
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
        //获取匿名队列名称
        String queueName = channel.queueDeclare().getQueue();
        //根据路由关键字进行多重绑定
        for (String severity : routingKeys) {
            channel.queueBind(queueName, EXCHANGE_NAME, severity);
            System.out.println("ReceiveLogsDirect2 exchange:"+EXCHANGE_NAME+", queue:"+queueName+", BindRoutingKey:" + severity);
        }
        System.out.println("ReceiveLogsDirect2 Waiting for messages");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws UnsupportedEncodingException, UnsupportedEncodingException {
                String message = new String(body, "UTF-8");
                System.out.println("ReceiveLogsDirect2 Received '" + envelope.getRoutingKey() + "':'" + message + "'");
            }
        };
        channel.basicConsume(queueName, true, consumer);
    }
}


这里是通过路由来找个这个对列的,效果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Topics 模糊匹配

1.生产者

package RabbitMQ;

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

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

/**
 * @author wzb
 * @date 2023/3/27  10:13
 */
public class TopicSend {
    private static final String EXCHANGE_NAME="topic_logs";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection=null;
        Channel channel=null;
        try {
            ConnectionFactory factory=new ConnectionFactory();
            factory.setHost("localhost");
            connection=factory.newConnection();
            channel=connection.createChannel();
            //声明一个匹配模式的交换机
            channel.exchangeDeclare(EXCHANGE_NAME,"topic");
            //待发送的消息
            String[] routingKeys=new String[]{
                "quick.orange.rabbit",
                 "lazy.orange.elephant",
                 "quick.orange.fox",
                    "lazy.brown.fox",
                    "quick.brown.fox",
                    "quick.orange.male.rabbit",
                    "lazy.orange.male.rabbit"
            };
            //发送消息
            for (String s:routingKeys) {
                String message="From "+s+" routingKey' s message!";
                channel.basicPublish(EXCHANGE_NAME,s,null,message.getBytes());
                System.out.println("TopicSend sent '"+s+"':'"+message+"'");
            }
        }catch (Exception e){
            e.printStackTrace();
            if (connection!=null){
                channel.close();
                connection.close();
            }
        }finally {
            if (connection!=null){
                channel.close();
                connection.close();
            }
        }
    }
}

2.消费者1

package RabbitMQ;

import com.rabbitmq.client.*;

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

/**
 * @author wzb
 * @date 2023/3/27  11:04
 */
public class ReceiveLogsTopics1 {
    private static final  String EXCHANGE_NAME="topic_logs";

    public static void main(String[] args) throws IOException, TimeoutException {

            ConnectionFactory factory=new ConnectionFactory();
            factory.setHost("localhost");
            Connection   connection=factory.newConnection();
            Channel channel=connection.createChannel();
            //声明一个匹配模式的交换机
            channel.exchangeDeclare(EXCHANGE_NAME,"topic");
            String queueName=channel.queueDeclare().getQueue();

            //路由关键字
            String[] routingKeys=new String[]{
              "*.orange.*"
            };

            //绑定路由
        for (String routingKKey:routingKeys) {
            channel.queueBind(queueName,EXCHANGE_NAME,routingKKey);
            System.out.println("ReceiveLogsTopic1 exchange:"+EXCHANGE_NAME+",queue:"+queueName+",BindRoutingKey:"+routingKKey);
        }
        System.out.println("ReceiveLogsTopic1 Waiting for message");
        Consumer consumer= new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message=new String(body,"UTF-8");
                System.out.println("ReceiveLogsTopic1 Received '"+envelope.getRoutingKey()+"':'" + message + "'");
            }
        };
channel.basicConsume(queueName,true,consumer);

    }
}

3.消费者2

package RabbitMQ;

import com.rabbitmq.client.*;

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

/**
 * @author wzb
 * @date 2023/3/27  11:04
 */
public class ReceiveLogsTopics2 {
    private static final  String EXCHANGE_NAME="topic_logs";

    public static void main(String[] args) throws IOException, TimeoutException {

            ConnectionFactory factory=new ConnectionFactory();
            factory.setHost("localhost");
            Connection   connection=factory.newConnection();
            Channel channel=connection.createChannel();
            //声明一个匹配模式的交换机
            channel.exchangeDeclare(EXCHANGE_NAME,"topic");
            String queueName=channel.queueDeclare().getQueue();

            //路由关键字
            String[] routingKeys=new String[]{
              "*.*.rabbit"
            };

            //绑定路由
        for (String routingKKey:routingKeys) {
            channel.queueBind(queueName,EXCHANGE_NAME,routingKKey);
            System.out.println("ReceiveLogsTopic2 exchange:"+EXCHANGE_NAME+",queue:"+queueName+",BindRoutingKey:"+routingKKey);
        }
        System.out.println("ReceiveLogsTopic2 Waiting for message");
        Consumer consumer= new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message=new String(body,"UTF-8");
                System.out.println("ReceiveLogsTopic2 Received '"+envelope.getRoutingKey()+"':'" + message + "'");
            }
        };
channel.basicConsume(queueName,true,consumer);

    }
}

效果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值