前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >07-RabbitMQ核心API-Direct Exchange

07-RabbitMQ核心API-Direct Exchange

作者头像
彼岸舞
发布2022-10-06 08:35:28
1540
发布2022-10-06 08:35:28
举报
文章被收录于专栏:java开发的那点事

Direct Exchange

简介

所有发送到direct exchange 的消息被转发到Routekey中指定的Queue

注意: Direct模式可以使用RabbitMQ自带的Exchange(default exchange), 所以不需要将Exchange进行任何Binding操作, 消息传递时RouteKey必须完全匹配才会被队列接收, 否则该消息会被丢弃

代码实现

RabbitMQHelper

代码语言:javascript
复制
package com.dance.redis.mq.rabbit;

import com.rabbitmq.client.*;

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

public class RabbitMQHelper {

    private static final String HOST = "192.168.247.142";
    private static final Integer PORT = 5672;
    private static final String VH = "/";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";
    private static final Boolean ARE = true;
    private static final Integer NRI = 3000;

    public static final String EXCHANGE_TYPE_DIRECT = "direct";
    public static final String EXCHANGE_TYPE_TOPIC = "topic";
    public static final String EXCHANGE_TYPE_FANOUT = "fanout";
    public static final String EXCHANGE_TYPE_HEADERS = "headers";

    private static Connection connection = null;

    public static Channel getChannel() throws IOException, TimeoutException {
        if (null == connection) {
            // 创建连接工厂
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost(HOST);
            connectionFactory.setPort(PORT);
            connectionFactory.setVirtualHost(VH);
            connectionFactory.setUsername(USERNAME);
            connectionFactory.setPassword(PASSWORD);
            connectionFactory.setAutomaticRecoveryEnabled(ARE);
            connectionFactory.setNetworkRecoveryInterval(NRI);
            connection = connectionFactory.newConnection();
        }
        return connection.createChannel();
    }

    public static AMQP.Exchange.DeclareOk exchangeDeclare(Channel channel, String exchangeName, String exchangeType) throws IOException {
        return channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
    }
    public static AMQP.Queue.DeclareOk queueDeclare(Channel channel, String queueName) throws IOException {
        return channel.queueDeclare(queueName, false, false, false, null);
    }

    public static void closeConnection() throws IOException {
        connection.close();
    }

    public static Consumer buildConsumer(Channel channel){
        return new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body)
            throws IOException {
                System.out.println("recvive message:" + new String(body));
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
    }

}

创建这个帮助类, 是为了减少一些通用代码的编写, 后续也会使用

消费者

代码语言:javascript
复制
package com.dance.redis.mq.rabbit.direct;

import com.dance.redis.mq.rabbit.RabbitMQHelper;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Consumer;

import java.util.concurrent.TimeUnit;
 
public class RabbitMQ4DirectExchangeConsumer {
 
    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMQHelper.getChannel();
        String exchangeName = "test_direct_exchange";
        String queueName = "test_direct_queue";
        String routingKey = "test_direct_routingKey";
        RabbitMQHelper.exchangeDeclare(channel,exchangeName,RabbitMQHelper.EXCHANGE_TYPE_DIRECT);
        RabbitMQHelper.queueDeclare(channel,queueName);
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.basicQos(64);//设置客户端最多接收未被ack的消息个数
        Consumer consumer = RabbitMQHelper.buildConsumer(channel);
        channel.basicConsume(queueName, consumer);
        //等待回调函数执行完毕之后,关闭资源。
        TimeUnit.SECONDS.sleep(50);
        channel.close();
        RabbitMQHelper.closeConnection();
    }
}

生产者

代码语言:javascript
复制
package com.dance.redis.mq.rabbit.direct;

import com.dance.redis.mq.rabbit.RabbitMQHelper;
import com.rabbitmq.client.Channel;
 
public class RabbitMQ4DirectExchangeProducer {
 
    
    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMQHelper.getChannel();
        String exchangeName = "test_direct_exchange";
        String routingKey = "test_direct_routingKey";
        String msg = "Hello World RabbitMQ 4  Direct Exchange Message ... ";
        channel.basicPublish(exchangeName, routingKey , null , msg.getBytes());
    }
    
}

测试

先启动消费者

然后启动生产者

查看消费者

已经收到了生产者的消息

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-10-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Direct Exchange
    • 简介
      • 代码实现
        • 测试
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档