custom message queue

  Traditional Netcom communication is generally request-response type. Taking TCP mode as an example, in the case of high concurrency, it is often accompanied by a large number of client Sokcet requests. The child thread to respond to the client's request will bring a lot of access pressure to the server.

  In this case, the message queue can be said to provide us with a new way of thinking. A queue is a linear table in a data structure. The elements stored in the queue follow the FIFO (First In First Out, first in first out) rule, which makes the elements in the queue orderly. We can regard the enqueue and dequeue of elements in the queue as production and consumption. In addition, combined with the publish-subscribe mode (listening mode), we can communicate between different threads through the queue.

  I am here to provide you with a simple custom message queue for reference.

package com.itszt.mq;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * A message queue listener, as long as the producer produces a message and pushes it into the queue, it will notify the processor to perform the consumption operation
 */
public class PushBlockQueue extends LinkedBlockingQueue<Object> {
    //Multi-threaded execution, using thread pool
    private static ExecutorService es = Executors.newFixedThreadPool(10);
    //Hungry mode in singleton, instantiate a queue singleton
    private static PushBlockQueue pbq = new PushBlockQueue();
    // status flag
    private boolean flag = false;

    private PushBlockQueue() {
    }

    public static PushBlockQueue getInstance() {
        return pbq;
    }

    /**
     * Queue monitor start
     */
    public void start() {
        if (!this.flag) {
            flag = true;
        } else {
            throw new IllegalArgumentException("The queue has been started and cannot be restarted!");
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (flag) {
                        // get message from queue
                        Object obj = take();
                        //The thread pool sends a thread to consume the fetched message
                        es.execute(new PushBlockQueueHandler(obj));
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
            }
        }).start();
    }

    /**
     * stop queue listening
     */
    public void stop(){
        this.flag=false;
    }
}
----------------------------------------------------
package com.itszt.mq;

/**
 * Equivalent to a consumer of queue messages
 */
public class PushBlockQueueHandler implements Runnable{
    // object to consume
    private Object obj;

    public PushBlockQueueHandler(Object obj){
        this.obj=obj;
    }
    //consumer thread
    @Override
    public void run() {
        doBusiness();
    }
    //consuming behavior
    private void doBusiness() {
        System.out.println(Thread.currentThread().getName()+" - received message : "+obj);
    }
}
-----------------------------------------------
package com.itszt.mq;

import java.util.Scanner;

/**
 * Custom message queue test class
 */
public class MQTest {
    public static void main(String[] args) {
        //Get the singleton of the message queue and start the queue listener
        PushBlockQueue.getInstance().start();
        //Write data to the queue in a loop
        /**
         * Producer----Produce message----"Enter queue----listener----notify consumer---"consumption
         */
        Scanner sc=new Scanner(System.in);
        try {
            while (true){
                String content = sc.nextLine();
                if(content.trim().equals("stop")){
                    System.exit(1);
                }
                PushBlockQueue.getInstance().put(content);
            }
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }
    }
}

   Start the program, and you (the main thread) can publish messages to other threads through the message queue in the console!

The Chinese dream, everyone's dream!
pool-1-thread-1-Received message: Chinese dream, everyone's dream!
Work tirelessly for the great rejuvenation of the Chinese nation!
pool-1-thread-2-Received the message: Unremitting struggle for the great rejuvenation of the Chinese nation!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326395224&siteId=291194637