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();
    }
}
相关推荐
布谷歌2 天前
Oops! 更改field的数据类型,影响到rabbitmq消费了...(有关于Java序列化)
java·开发语言·分布式·rabbitmq·java-rabbitmq
一个假的前端男2 天前
RabbitMQ 消息队列 优化发送邮件
分布式·rabbitmq·ruby
A尘埃2 天前
关闭超时订单和七天自动确认收货+RabbitMQ规范
分布式·rabbitmq
m0_748241232 天前
RabbitMq 基础
分布式·rabbitmq·ruby
星星点点洲2 天前
【RabbitMQ业务幂等设计】RabbitMQ消息是幂等的吗?
rabbitmq
劉煥平CHN2 天前
RabbitMQ的脑裂(网络分区)问题
网络·分布式·rabbitmq
火皇4053 天前
Spring Boot 集成 RabbitMQ 并实现消息确认机制
spring boot·rabbitmq·java-rabbitmq
何似在人间5753 天前
RabbitMQ 消息队列的工作模式
分布式·rabbitmq
一條狗3 天前
20250219 隨筆 [特殊字符] 查看短鏈的實現方式與解決方案優化
rabbitmq·冗餘雙寫
小猫猫猫◍˃ᵕ˂◍3 天前
rabbitmq五种模式的实现——springboot
spring boot·rabbitmq·java-rabbitmq