消息中间件--RabbitMQ学习(四)

入门构建消息生产以及消费

  1. Queue:具体的消息存储队列
  2. Producer& Consumer生产和消费者

具体代码实现

引入maven包

		<dependency>
			<groupId>com.rabbitmq</groupId>
			<artifactId>amqp-client</artifactId>
			<version>3.6.5</version>
		</dependency>

消费端

public class Consumer {

    public static void main(String[] args) throws Exception{
        //1 创建一个connectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.0.159");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        //2通过连接工场创建连接
        Connection connection = connectionFactory.newConnection();
        //3通过connection创建channel
        Channel channel = connection.createChannel();

        //4创建一个队列
        channel.queueDeclare("test001",true,false,false,null);

        //5创建一个消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
        //设置channel
        channel.basicConsume("test001",true,queueingConsumer);
        while (true){
            //7获取消息
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("消费者" + msg);
            Envelope envelope = delivery.getEnvelope();
        }
    }
}

生产者

public class Producter {
    public static void main(String[] args) throws Exception{
        //1 创建一个connectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.0.159");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        //2通过连接工场创建连接
        Connection connection = connectionFactory.newConnection();
        //3通过connection创建channel
        Channel channel = connection.createChannel();
        //4通过Cchannel发送数据
        for(int i=0;i<5;i++){
            String msg = "HELLO";
            channel.basicPublish("","test001",null,msg.getBytes());
        }
        channel.close();
        connection.close();
    }
}
  1. 启动Consumer 端,在RabbitMQ的控制台上可以看到创建的交换机以及队列。
  2. 启动Producter ,发送5条数据到Consumer ,在Consumer 控制台就可以看到接收到的消息。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值