Java模拟消息队列

今天面大数据架构师实习生,被问到怎么使用Java来实现简单的消息队列,,一脸懵逼,,,

package com;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * created by LMR on 2019/7/10
 */
public class ProducerAndConsumer {

    public static void main(String[] args) {
        BlockingQueue blockingQueue = new ArrayBlockingQueue(10);
        Producer producer = new Producer(blockingQueue);

        //启动一个消费者
        Consumer consumer = new Consumer(blockingQueue);
        Thread consumerThread = new Thread(consumer);
        consumerThread.start();

        int n = 0;
        //模拟生产者发消息
        while (true){
            Message message = new Message();
            message.setTopic("hello("+n+")");
            message.setBody("nice to meet you("+n+")");
            System.out.println("发送消息:"+message.toString());
            producer.send(message);
            n++;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

class Producer{
    private BlockingQueue messageQueue;
    private volatile  Message message;
    public Message getMessage() {
        return message;
    }

    public void setMessage(Message message) {
        this.message = message;
    }


    public Producer(BlockingQueue messageQueue){
        this.messageQueue = messageQueue;
    }

    public void send(Message message){
        try {
            this.messageQueue.put(message);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class Consumer implements Runnable{
    private volatile Message message;
    private String topic;
    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }
    private BlockingQueue blockingQueue;
    public Consumer(BlockingQueue blockingQueue){
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        while (true) {
            if (!blockingQueue.isEmpty()) {
                try {
                    System.out.println("收到消息:" + blockingQueue.take().toString());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
class Message {
    private String topic;
    private String body;

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    @Override
    public String toString() {
        return "{topic:" + topic + ",body:" + body + "}";
    }

}

 

你可能感兴趣的:(消息队列,Java,JAVA)