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();
    }
}
相关推荐
DavidSoCool12 小时前
RabbitMQ使用topic Exchange实现微服务分组订阅
分布式·微服务·rabbitmq
Bug退退退12318 小时前
RabbitMQ 高级特性之重试机制
java·分布式·spring·rabbitmq
Bug退退退1231 天前
RabbitMQ 高级特性之死信队列
java·分布式·spring·rabbitmq
m0_474606781 天前
RabbitMQ使用延迟插件实现延迟消息
java·rabbitmq
幼稚园的山代王2 天前
RabbitMQ 4.1.1初体验-队列和交换机
分布式·rabbitmq·ruby
csdn_aspnet3 天前
在 Windows 机器上安装和配置 RabbitMQ
windows·rabbitmq
Bug退退退1233 天前
RabbitMQ 高级特性之 TTL
java·分布式·spring·rabbitmq
幼稚园的山代王3 天前
RabbitMQ 4.1.1初体验
分布式·rabbitmq·ruby
csdn_aspnet3 天前
Windows Server 上的 RabbitMQ 安装和配置
windows·rabbitmq
百锦再3 天前
RabbitMQ用法的6种核心模式全面解析
分布式·rabbitmq·路由·消息·通道·交换机·代理