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();
    }
}
相关推荐
子非衣1 小时前
CenOS7安装RabbitMQ(含延迟队列插件)
分布式·rabbitmq·ruby
独自破碎E2 小时前
说说RabbitMQ的集群模式
rabbitmq
利刃大大4 小时前
【RabbitMQ】重试机制 && TTL && 死信队列
分布式·后端·消息队列·rabbitmq·队列
论迹1 天前
【RabbitMQ】-- 七种工作模式
分布式·rabbitmq
论迹1 天前
【RabbitMQ】-- 高级特性
数据库·redis·分布式·消息队列·rabbitmq
我爱娃哈哈1 天前
SpringBoot + Canal + RabbitMQ:MySQL 数据变更实时同步到缓存与搜索系统
spring boot·rabbitmq·java-rabbitmq
利刃大大1 天前
【RabbitMQ】消息确认机制 && 持久化 && 发布确认机制
分布式·中间件·消息队列·rabbitmq·mq
xiaolyuh1231 天前
RabbitMQ 深度详解
分布式·rabbitmq
Overt0p1 天前
抽奖系统(7)
java·开发语言·spring boot·redis·tomcat·rabbitmq
D_FW1 天前
【Java】SpringAMQP+RabbitMQ消息可靠性保证
java·rabbitmq·java-rabbitmq