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

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

相关推荐
YOU OU25 分钟前
Redis分布式锁
数据库·redis·分布式
小罗水3 小时前
第9章 RabbitMQ 消息队列与索引任务
分布式·rabbitmq
naierfengdian4 小时前
分布式风力发电机机抗风扰、稳发电结构设计技术解析
分布式·能源
wWYy.13 小时前
基于Raft分布式Kv存储:sendRequestVote
分布式
笨鸟先飞的橘猫21 小时前
游戏后端分布式学习——消息队列在游戏的用法
分布式·学习·游戏
Wang's Blog1 天前
Go-Zero项目开发40: 基于Jaeger的分布式链路跟踪实战
开发语言·分布式·golang
wWYy.1 天前
基于Raft分布式Kv存储:sendAppendEntries
分布式
范什么特西1 天前
关于kafka
分布式·kafka
wWYy.1 天前
基于Raft分布式Kv存储:AppendEntries
分布式
霸道流氓气质1 天前
分布式系统中跨进程上下文传递方案
分布式