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", " ");
    }
}
相关推荐
linux修理工8 小时前
使用codebuddy学习kafka
分布式·学习·kafka
阿 才8 小时前
跟文件系统(busybox)的构建
大数据·hadoop·分布式
老纪9 小时前
Redis分布式锁进第九零篇
数据库·redis·分布式
Amy187021118239 小时前
分布式光伏防孤岛保护:技术逻辑、标准演进与工程实践全解析
分布式
ACP广源盛1392462567310 小时前
IX7008 PCIe 交换芯片@ACP#RTX Spark 经济型 8 口扩展芯片(对比 ASM1806)
大数据·人工智能·分布式·嵌入式硬件·gpt·spark·电脑
ACP广源盛1392462567311 小时前
IX6012 PCIe 交换芯片@ACP#RTX Spark 入门级 12 口存储外设扩展方案(对比 ASM1812)
大数据·人工智能·分布式·嵌入式硬件·gpt·spark·电脑
分布式存储与RustFS12 小时前
对标MinIO!RustFS新一代AI分布式对象存储开源能力前瞻
人工智能·分布式·开源·分布式对象存储·rustfs·minio平替·s3 table
cxr82814 小时前
蜂群智能系统中“非必要不添加“原则的有效性再审视:基于分布式决策与通信复杂度的理论推导
人工智能·分布式·智能体
bIo7lyA8v14 小时前
算法工程中的可扩展性与分布式实现方案的技术8
分布式
我登哥MVP14 小时前
SpringCloud 核心组件解析:分布式配置管理
java·spring boot·分布式·spring·spring cloud·java-ee·maven