RabbitMq快速入门程序

这个入门程序就是为了体验RabbitMq消息传递的过程

生产者代码:

引入依赖:

复制代码
<dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>5.26.0</version>
</dependency>
java 复制代码
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ProducerDemon {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory =new ConnectionFactory();
        connectionFactory.setUsername("study");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("study");
        connectionFactory.setPassword("123456");
        connectionFactory.setHost("192.168.46.107");
        //创建连接 Connection
        Connection connection = connectionFactory.newConnection();
        //创建 信道:Channel
        Channel channel = connection.createChannel();
        //声明交换机,这里使用默认的交换机

        //声明队列
        channel.queueDeclare("study",false,false,false,null);
        //发送消息
        String msg="你好";
        channel.basicPublish("","study",null,msg.getBytes());
        System.out.println("消息发送成功");
        channel.close();
        connection.close();


    }
}

消费者代码:

java 复制代码
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerDemon {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setHost("192.168.46.107");
        connectionFactory.setUsername("study");
        connectionFactory.setPassword("123456");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("study");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息:"+new String(body));
            }
        };
        channel.basicConsume("study", true, consumer);
    }
}

上述代码可以直接赋值,改一下其中的参数即可.

相关推荐
初次攀爬者2 天前
ZooKeeper 实现分布式锁的两种方式
分布式·后端·zookeeper
让我上个超影吧3 天前
消息队列——RabbitMQ(高级)
java·rabbitmq
塔中妖3 天前
Windows 安装 RabbitMQ 详细教程(含 Erlang 环境配置)
windows·rabbitmq·erlang
断手当码农3 天前
Redis 实现分布式锁的三种方式
数据库·redis·分布式
初次攀爬者3 天前
Redis分布式锁实现的三种方式-基于setnx,lua脚本和Redisson
redis·分布式·后端
业精于勤_荒于稀3 天前
物流订单系统99.99%可用性全链路容灾体系落地操作手册
分布式
Ronin3053 天前
信道管理模块和异步线程模块
开发语言·c++·rabbitmq·异步线程·信道管理
Asher05093 天前
Hadoop核心技术与实战指南
大数据·hadoop·分布式
凉凉的知识库3 天前
Go中的零值与空值,你搞懂了么?
分布式·面试·go
?Anita Zhang3 天前
联邦学习实战:如何在分布式场景下构建隐私保护机器学习模型
人工智能·分布式·机器学习