rabbitmq服务端消费端实例(direct和fanout模式)

  1. 配置文件
java 复制代码
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
 */
public class RabbitMQConnectionUtilLocal {
    public static Connection getConnection() throws Exception {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置RabbitMQ主机地址
        factory.setHost("localhost");
        // 设置RabbitMQ端口
        factory.setPort(5672);
        // 设置虚拟主机、用户名和密码
        factory.setVirtualHost("/");
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setAutomaticRecoveryEnabled(true); // 自动重连


        // 返回连接
        return factory.newConnection();
    }
}
  1. direct生产端
java 复制代码
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

public class RoutingProducer {
    private final static String EXCHANGE_NAME = "direct_exchange";

    public static void main(String[] argv) throws Exception {
        // 获取到连接
        Connection connection = RabbitMQConnectionUtil.getConnection();
        // 从连接中创建通道
        Channel channel = connection.createChannel();

        // 声明交换器
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");

        // 发送消息
        String message1 = "{\"flag\":0,\"idList\":[\"1\"]}";
        String message2 = "Info log message";
        String message3 = "Warning log message";

        channel.basicPublish(EXCHANGE_NAME, "error", null, message1.getBytes());
        System.out.println(" [x] Sent '" + message1 + "'");

        channel.basicPublish(EXCHANGE_NAME, "info", null, message2.getBytes());
        System.out.println(" [x] Sent '" + message2 + "'");

        channel.basicPublish(EXCHANGE_NAME, "warning", null, message3.getBytes());
        System.out.println(" [x] Sent '" + message3 + "'");

        // 关闭通道和连接
        channel.close();
        connection.close();
    }
}
  1. fanout生产端
java 复制代码
import com.rabbitmq.client.*;
import jzy.util.RabbitMQConnectionUtil;

public class FanoutExchangeExample {
    private static final String EXCHANGE_NAME = "20250917test1";

    public static void main(String[] argv) throws Exception {
        Connection connection = RabbitMQConnectionUtilLocal.getConnection();
        Channel channel = connection.createChannel();

        // 声明Fanout类型的交换器,第三个参数是持久化标记
        channel.exchangeDeclare(EXCHANGE_NAME, "fanout",true);

        // 创建队列并绑定到交换器
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, EXCHANGE_NAME, "");

        // 发送消息
        String message = "This is a log message";
        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes("UTF-8"));
        System.out.println(" [x] Sent '" + message + "'");

        channel.close();
        connection.close();
    }
}
  1. 消费端
java 复制代码
package jzy.util;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.rabbitmq.client.*;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

public class RabbitMQConsumer {
//    private final static String EXCHANGE_NAME = "direct_exchange";
//    private final static String QUEUE_NAME = "error_log_queue";

    private final static String EXCHANGE_NAME = "position_exchange";
    private final static String QUEUE_NAME = "LZF0101_queue";

    public static void main(String[] argv) throws Exception {
        // 获取到连接
        Connection connection = RabbitMQConnectionUtil.getConnection();
        // 从连接中创建通道
        Channel channel = connection.createChannel();

        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        // 绑定队列到交换器,并指定路由键
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "LZF0101_topic");

        // 定义队列的消费者
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws java.io.IOException {
                String message = new String(body, "UTF-8");
                JSONObject jsonObject = JsonUtil.getJsonToBean(replaceNbspWithSpace(message), JSONObject.class);
                try {
                    switch (jsonObject.getStr("flag")) {
                     
                        default:
                            break;
                    }
                } catch (Exception e) {
               
                    throw new RuntimeException(e);
                }
                System.out.println(" [x] Received  Log: '" + message + "'");
            }
        };

        // 监听队列
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }

    /**
     * 正则过滤生产端信息特殊符号,过滤 NBSP
     */
    public static String replaceNbspWithSpace(String str) {
        if (str == null) {
            return null;
        }
        return str.replaceAll("\\u00A0", " ");
    }
}
相关推荐
我认不到你17 分钟前
paxos一致性算法(大白话+图解)
分布式·后端
川2125 分钟前
Kafka消息中间件(超大数据吞吐量)使用
分布式·kafka
Wang's Blog1 小时前
Kafka: 基于 NestJS 的问卷系统配置与业务实现
分布式·kafka
回家路上绕了弯1 小时前
一文读懂分布式事务:核心原理、解决方案与实践思考
分布式·后端
踏浪无痕1 小时前
JobFlow 背后:五个让我豁然开朗的设计瞬间
分布式·后端·架构
我是小妖怪,潇洒又自在1 小时前
springcloud alibaba(十)分布式事务
分布式·spring cloud·wpf
Q8762239651 小时前
基于S7 - 200 PLC和组态王的大小球颜色大小材质分拣系统探索
分布式
小满、2 小时前
RabbitMQ:Fanout、Direct、Topic 交换机、队列声明与消息转换器
java·分布式·消息队列·rabbitmq·spring amqp
Wang's Blog3 小时前
RabbitMQ: 分布式事务的最终一致性解决方案
分布式·rabbitmq
低调电报3 小时前
我的第一个开源项目:鸿蒙分布式“口袋健身”教练
分布式·开源·harmonyos