RabbitMQ

rabbitmq官网:https://www.rabbitmq.com/

rabbitmq是erlang开发的,需要安装erlang环境

Erlang是一种功能编程语言,也具有运行时环境。

Erlang官网:https://www.erlang.org/


获取连接

java 复制代码
public class RabbitMQConnection {
    public static Connection getConnection() throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        // 设置连接虚拟机
        connectionFactory.setVirtualHost("/meiteVirtualHosts");
        // 设置账号密码
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        // 设置ip和端口
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        return connectionFactory.newConnection();
    }
}

生产者

java 复制代码
public class Producer {
    public static final String QUEUE_NAME = "queue-name";
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接
        Connection connection = RabbitMQConnection.getConnection();
        // 创建通道
        Channel channel = connection.createChannel();
        String msg = "消息-" + new Date();
        // 发布消息到队列
        channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());
        // 关闭通道和连接
        channel.close();
        connection.close();
    }
}

消费者

java 复制代码
public class Comsumer {
    public static final String QUEUE_NAME = "queue-name";
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接
        Connection connection = RabbitMQConnection.getConnection();
        // 创建通道
        Channel channel = connection.createChannel();
        // 消费消息
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者:" + new String(body, StandardCharsets.UTF_8));
            }
        };
        // 监听队列 autoAck:true自动签收,false手动签收
        channel.basicConsume(QUEUE_NAME,true,defaultConsumer);
        // 长连接不必关闭通道
        //channel.close();
        //connection.close();
    }
}
相关推荐
sukioe6 小时前
从 0 到 1 构建城市公共设施智能报修与派单系统:FastAPI + Vue3 + RabbitMQ + Redis Geo + AI 工作流实践
redis·rabbitmq·fastapi
止语Lab5 天前
一次 goroutine 泄漏:pprof 说有 10 万个 goroutine,但问题不在 channel
rabbitmq
JLWcai2025100920 天前
铸造领域树脂砂轮|金利威多场景解决方案,20 + 配方覆盖全需求
mongodb·zookeeper·eureka·spark·rabbitmq·memcached·storm
风吹夏回20 天前
RabbitMQ 核心术语 + Python pika 方法完整讲解
分布式·python·rabbitmq
风吹夏回20 天前
RabbitMQ 三种模式入门:HelloWorld、WorkQueue、PubSub
分布式·rabbitmq·ruby
cheems952720 天前
[RabbitMQ高级特性] 消息确认机制:从 Ready / Unacked 到 basicAck、basicReject、basicNack 的底层拆解
分布式·rabbitmq·ruby
半夜修仙21 天前
延迟队列的介绍及常见问题
java·数据库·中间件·rabbitmq
Solis程序员21 天前
Raft:分布式系统的定海神针
java·分布式·kafka·rabbitmq·agent·raft
手握风云-21 天前
一条消息的旅程:RabbitMQ 学习与实践(一)
中间件·rabbitmq
Zyangxsir21 天前
RabbitMQ 核心概念以及Java(Spring Boot)实战用法的整理
java·spring boot·后端·rabbitmq·java-rabbitmq