Java笔记-使用RabbitMQ的Java接口生产数据并消费

目录

 

 

基本概念

代码及演示


 

基本概念

就是官方的这个模型:

p为生产者不经过交换机,直接把数据传给消息队列,c为consumer用于消费。

这种结构在本科生的时候,经常自己写,现在用RabbitMQ来试试

 

 

代码及演示

发送端点击运行:

Java笔记-使用RabbitMQ的Java接口生产数据并消费_第1张图片

消费者那边会接收到数据:

Java笔记-使用RabbitMQ的Java接口生产数据并消费_第2张图片

关键的源码如下:

Maven依赖:



        
            com.rabbitmq
            amqp-client
            5.4.3
        

        
            org.slf4j
            slf4j-api
            1.7.25
        

        
            org.slf4j
            slf4j-log4j12
            1.7.5
        

        
            log4j
            log4j
            1.2.17
        

        
            junit
            junit
            4.12
        

    

生产者:

package rabbitmq.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import rabbitmq.util.ConnectionUtils;

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

public class Send {

    private static final String QUEUE_NAME = "test_simple_queue";

    public static void main(String[] args) throws IOException, TimeoutException {

        Connection connection = ConnectionUtils.getConnect();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String msg = "Hello World";
        channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());

        System.out.println("---send msg: " + msg);
        channel.close();
        connection.close();
    }
}

 

消费者:

package rabbitmq.simple;

import com.rabbitmq.client.*;
import rabbitmq.util.ConnectionUtils;

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

public class Recv {

    private static final String QUEUE_NAME = "test_simple_queue";

    public static void main(String[] args) throws IOException, TimeoutException {

        Connection connection = ConnectionUtils.getConnect();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);    //声明,没有就会创建
        DefaultConsumer consumer = new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                String msg = new String(body, "utf-8");
                System.out.println("recv: " + msg);
            }
        };

        //监听
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }
}

这里有一点要注意的:

basicConsume里的第二个参数是true,的意思是给消息队列一个应答,说明,我已经拿出来了!他是一个ack

程序打包下载地址:

https://github.com/fengfanchen/Java/tree/master/SimpleRabbitMQ

你可能感兴趣的:(Java,RabbitMQ)