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();
    }
}
相关推荐
Devin~Y2 天前
大厂Java面试实录:Spring Boot微服务 + Redis缓存 + Kafka消息队列 + Prometheus链路追踪 + RAG向量检索
java·spring boot·redis·spring cloud·kafka·rabbitmq·spring mvc
phltxy2 天前
RabbitMQ 入门与安装
分布式·rabbitmq
逻极2 天前
RabbitMQ 从入门到精通:构建高可用、高性能的消息中间件系统
分布式·rabbitmq·消息中间件
Jinkxs2 天前
SkyWalking - Kafka _ RabbitMQ 消息链路追踪支持
kafka·rabbitmq·skywalking
武子康3 天前
Java-221 RocketMQ 消息存储核心原理:CommitLog、ConsumerQueue、IndexFile 与消息过滤机制
java·大数据·分布式·消息队列·rabbitmq·rocketmq·java-rocketmq
Albert Edison3 天前
基于 SpringBoot + RabbitMQ 完成企业级应用通信
spring boot·rabbitmq·java-rabbitmq
随风,奔跑3 天前
RabbitMQ
后端·rabbitmq
或与且与或非4 天前
rabbitmq选举集群搭建
分布式·rabbitmq·ruby
BIG_PEI4 天前
如何判断Linux服务器上是否安装了rabbitmq
linux·服务器·rabbitmq
阿正的梦工坊4 天前
RabbitMQ 消息队列详解:从原理到实战
分布式·rabbitmq