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);
    }
}

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

相关推荐
DoveLx4 小时前
RabbitMQ:构建高可用异步通信系统的基石
消息队列·rabbitmq
数智顾问6 小时前
破解 Shuffle 阻塞:Spark RDD 宽窄依赖在实时特征工程中的实战与未来
大数据·分布式·spark
JAVA学习通7 小时前
Kafka在美团数据平台的实践
分布式·kafka
JAVA学习通8 小时前
Replication(下):事务,一致性与共识
大数据·分布式·算法
失散1311 小时前
分布式专题——45 ElasticSearch基础数据管理详解
java·分布式·elasticsearch·架构
没有bug.的程序员11 小时前
分布式监控体系:从指标采集到智能告警的完整之道
java·分布式·告警·监控体系·指标采集
没有bug.的程序员18 小时前
服务网格 Service Mesh:微服务通信的终极进化
java·分布式·微服务·云原生·service_mesh
笨手笨脚の1 天前
Kafka-1 初识消息引擎系统
分布式·kafka·消息队列·消息引擎系统
Savvy..1 天前
消息队列MQ
kafka·消息队列·rabbitmq·rocketmq·mq