学习RabbitMQ五种队列

本文参考学习了:

RabbitMQ超详细学习笔记
RabbitMQ使用教程

image

Java代码示例

public class ConnectionFactoryHolder {
    private final static ConnectionFactory connectionFactory;

    static {
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            factory.setPort(5672);
            connectionFactory = factory;
        } catch (Exception e) {
            throw new RuntimeException("Failed to create connection factory", e);
        }
    }

    public static ConnectionFactory getConnectionFactory(String username, String password, String virtualHost) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername(username);
        factory.setPassword(password);
        factory.setVirtualHost(virtualHost);
        return factory;
    }

    public static ConnectionFactory getConnectionFactory() {
        return connectionFactory;
    }

    public static Connection newConnection() throws IOException, TimeoutException {
        return getConnectionFactory().newConnection();
    }

}
public class InternalConsumer implements DeliverCallback {
    private final String name;
    private final String queueName;
    private final Channel channel;
    private final boolean autoAck;

    public InternalConsumer(Channel channel, String queueName, boolean autoAck) {
        this.channel = channel;
        this.queueName = queueName;
        this.name = "Consumer-" + queueName;
        this.autoAck = autoAck;
    }

    @Override
    public void handle(String consumerTag, Delivery delivery) {
        try {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(name + " Received message: " + message);
            if (!autoAck) {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public void basic() throws IOException {
        channel.basicConsume(queueName, autoAck, this, consumerTag -> {
        });
    }
}

简单队列/Work模式:

生产消息


public class SimpleSend {

    public final static String QUEUE_NAME = "test";

    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionFactoryHolder.getConnectionFactory().newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        AtomicInteger atomicInteger = new AtomicInteger(0);
        Runnable r = () -> {
            for (; atomicInteger.get() < 1; atomicInteger.incrementAndGet()) {
                String message = "Message#" + atomicInteger.get();
                try {
                    channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8));
                    System.out.println(" [x] Sent '" + message + "'");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        };
        r.run();
//        new Thread(r).start();
//        new Thread(r).start();
    }
}

消费消息

public class SimpleConsumers {
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionFactoryHolder.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(SimpleSend.QUEUE_NAME, true, false, false, null);
//        channel.basicQos(1);
//        System.out.println("Consumer " + 1 + " started");
//        channel.basicConsume(Send.QUEUE_NAME, false,
//                new InternalConsumer(channel, "consumer" + 1), consumerTag -> {
//                });
        ExecutorService executor = Executors.newFixedThreadPool(20);
        for (int i = 0; i < 20; i++) {
            int finalI = i;
            executor.execute(() -> {
                try {
                    Channel cl = connection.createChannel();
                    cl.basicQos(1);
                    System.out.println("Consumer " + finalI + " started");
                    new InternalConsumer(cl, SimpleSend.QUEUE_NAME, false).basic();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        // 关闭线程池(这里只是为了展示,实际应用中应根据业务逻辑决定何时关闭)
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(800, java.util.concurrent.TimeUnit.MILLISECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException ie) {
                executor.shutdownNow();
            }
        }));
    }
}

订阅模式

生产消息

public class FanoutSend {
    public static final String EXCHANGE_NAME = "fanout_logs";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = ConnectionFactoryHolder.getConnectionFactory();
        try (Connection connection = connectionFactory.newConnection();
             Channel channel = connection.createChannel()) {

            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);

            String message = "Hello World!";
            channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
            System.out.println(" [x] Sent '" + message + "'");
        }
    }
}

消费消息

public class FanoutConsumers {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = ConnectionFactoryHolder.getConnectionFactory();
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(FanoutSend.EXCHANGE_NAME, BuiltinExchangeType.FANOUT);

        String queueName1 = "fanout_test1";
        channel.queueDeclare(queueName1, true, false, false, null);
        String queueName2 = "fanout_test2";
        channel.queueDeclare(queueName2, true, false, false, null);


        channel.queueBind(queueName1, FanoutSend.EXCHANGE_NAME, "");
        channel.queueBind(queueName2, FanoutSend.EXCHANGE_NAME, "");

        new InternalConsumer(channel, queueName1, false).basic();
        new InternalConsumer(channel, queueName2, false).basic();
    }
}

路由模式

生产消息

public class DirectSend {
    public static final String EXCHANGE_NAME = "direct_logs";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = ConnectionFactoryHolder.getConnectionFactory();
        try (Connection connection = connectionFactory.newConnection();
             Channel channel = connection.createChannel()) {

            channel.exchangeDeclare(EXCHANGE_NAME, "direct");

            channel.basicPublish(EXCHANGE_NAME, "error", null, "error".getBytes());
            channel.basicPublish(EXCHANGE_NAME, "info", null, "info".getBytes());
            channel.basicPublish(EXCHANGE_NAME, "wran", null, "wran".getBytes());
            channel.basicPublish(EXCHANGE_NAME, "debug", null, "debug".getBytes());
            channel.basicPublish(EXCHANGE_NAME, "", null, "empty".getBytes());
        }
    }
}

消费消息

public class DirectConsumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = ConnectionFactoryHolder.getConnectionFactory();
        Connection connection = connectionFactory.newConnection();

        Channel channel = connection.createChannel();
        channel.exchangeDeclare(DirectSend.EXCHANGE_NAME, "direct");

        String queue1 = "direct_test1";
        channel.queueDeclare(queue1, true, false, false, null);
        channel.queueBind(queue1, DirectSend.EXCHANGE_NAME, "error");
        channel.queueBind(queue1, DirectSend.EXCHANGE_NAME, "info");
        channel.queueBind(queue1, DirectSend.EXCHANGE_NAME, "wran");
        channel.queueUnbind(queue1, DirectSend.EXCHANGE_NAME, "");

        String queue2 = "direct_test2";
        channel.queueDeclare(queue2, true, false, false, null);
        channel.queueBind(queue2, DirectSend.EXCHANGE_NAME, "info");
        channel.queueBind(queue2, DirectSend.EXCHANGE_NAME, "debug");
        channel.queueBind(queue2, DirectSend.EXCHANGE_NAME, "");

        new InternalConsumer(channel, queue1, false).basic();
        new InternalConsumer(channel, queue2, false).basic();
    }
}

主题模式

生产消息

public class TopicSend {
    public static final String EXCHANGE_NAME = "topic_logs";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = ConnectionFactoryHolder.getConnectionFactory();
        try (Connection connection = connectionFactory.newConnection();
             Channel channel = connection.createChannel()) {

            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);

            channel.basicPublish(EXCHANGE_NAME, "log.error", null, "error".getBytes());
            channel.basicPublish(EXCHANGE_NAME, "log.info", null, "info".getBytes());
            channel.basicPublish(EXCHANGE_NAME, "log.wran", null, "wran".getBytes());
            channel.basicPublish(EXCHANGE_NAME, "log.debug", null, "debug".getBytes());
            channel.basicPublish(EXCHANGE_NAME, "log.debug.important.abc", null, "debug important".getBytes());
            channel.basicPublish(EXCHANGE_NAME, "", null, "empty".getBytes());
        }
    }
}

消费消息

public class TopicConsumers {
    public static final String EXCHANGE_NAME = TopicSend.EXCHANGE_NAME;

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = ConnectionFactoryHolder.getConnectionFactory();
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);

        String queueName1 = "topic_test1";
        channel.queueDeclare(queueName1, true, false, false, null);
        channel.queueBind(queueName1, EXCHANGE_NAME, "log.*");
        channel.queueBind(queueName1, EXCHANGE_NAME, "log.*.*.abc");

        String queueName2 = "topic_test2";
        channel.queueDeclare(queueName2, true, false, false, null);
        channel.queueBind(queueName2, EXCHANGE_NAME, "log.#");
        channel.queueBind(queueName2, EXCHANGE_NAME, "");

        new InternalConsumer(channel, queueName1, false).basic();
        new InternalConsumer(channel, queueName2, false).basic();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,377评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,390评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,967评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,344评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,441评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,492评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,497评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,274评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,732评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,008评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,184评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,837评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,520评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,156评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,407评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,056评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,074评论 2 352