Java - a message queue based on LinkedList

Kind little black brother 2021-01-22 15:49:02
java message queue based linkedlist


Preface

Daily development , There are two main sets that we use most , One is ArrayList, One is LinkedList

If the ArrayList There are students who don't understand , Take a look at an article I wrote before :Java aggregate ,ArrayList Source code in-depth analysis

So this article , We are mainly based on LinkedList Write a simple queue .


Design thinking :

First of all, when we want to design a plan , First of all, we need to clear our thinking , Think about the existing , What others have achieved , Then think about how you can achieve it .( such as rabbitMq)

Queue management center : Centralized management of all created queues

provider : Sending messages to message queues

Consumer : Listen for messages in the message queue , And consume ( If you listen to a new message in the queue , Automatic consumption processing )

First step : Implement message queuing

We need to be clear about what the queue needs to do , It's mainly about sending messages , receive messages .
package com.dm.black.modules.myQuere;
import java.util.LinkedList;
/**
* be based on LinkedList Implement message queuing
* @author wjy
* @date 2021/1/20
*/
public class MQueue extends QueueCenter {
private LinkedList<Object> queue = new LinkedList<>();
/**
* Be careful : The purpose of locking is to prevent concurrent operations , because LinkedList Itself is thread unsafe
* @method Put message
* @param o
* @return
*/
public boolean putMessage(Object o) {
synchronized (queue) {
// If the queue is waiting , Then perform wake-up
if (queue.isEmpty()) {
System.out.println(" Wake up the queue ...");
queue.notifyAll();
}
// Put messages in the queue
queue.push(o);
return true;
}
}
/**
* @method Get the news ( Get the first message and delete )
* @return
*/
public Object pollFirst() {
synchronized (queue) {
// If there are no messages in the queue , It's blocked , When there is news, consume
if (queue.isEmpty()) {
try {
System.out.println(" There is no data in the queue , Start the waiting ....");
queue.wait();
// After being awakened , So let's keep going
Object o = queue.pollFirst();
return o;
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
Object o = queue.pollFirst();
return o;
}
}
return null;
}
/**
* Get the news ( Get the first message without deleting it )
* @return
*/
public Object getFrist(){
synchronized (queue) {
Object first = queue.getFirst();
return first;
}
}
/**
* Whether there is a message in the queue
* @return
*/
public boolean isReady() {
if (!queue.isEmpty()) {
return true;
}
return false;
}
} 

The second step : Implement message queue management center

Purpose : To unify queue management , such as N Two registrants , perhaps  N When two consumers use a queue with the same name , Ensure that the operation is on the same queue .
package com.dm.black.modules.myQuere;
import java.util.HashMap;
import java.util.Map;
/**
* Queue-center
* @author wjy
* @date 2021/1/20
*/
public class QueueCenter {
/**
* @description Use here Map As a queue management center
* Create a queue Management Center , All created Queue Manage here
* Map -> key : queue name
* Map -> value : queue
*/
private static Map<String, MQueue> queueCenter = new HashMap<>();
/**
* @method from Queue-center obtain Queue
* Locking purpose : Prevent the creation of... With the same name at the same time queue
*/
public static MQueue getQueue(String queueName) {
synchronized (queueName) {
// from map Get the queue by name in , If it already exists , Then return to map The queue in
MQueue queue = queueCenter.get(queueName);
// If this is the first time a queue has been created , Then create a new queue and put it in map, Then return the new queue to
if (queue == null) {
queue = new MQueue();
putQueue(queueName, queue);
MQueue mQueue = queueCenter.get(queueName);
return mQueue;
}
return queue;
}
}
/**
* @method take Queue Put in Queue-center
* @param queueName
*/
private static void putQueue(String queueName, MQueue queue) {
queueCenter.put(queueName, queue);
}
} 

The third step : Message registration

We want to achieve a provider , Put messages in the queue , For consumer use
package com.dm.black.modules.myQuere;
/**
* Registrant
* @author wjy
* @date 2021/1/20
*/
public class MProvider {
// Queue name
private final String queueName = "demo";
/**
* Send a message to 'demo' queue
* @param message
*/
public void sendMessage(String message) {
// Get queue
MQueue queue = QueueCenter.getQueue(queueName);
// Put message
queue.putMessage(message);
System.out.println(" Provider :" + queueName + ": Send a message :" + message);
}
} 

Step four : Messenger implementation

So this is actually where , Message registration and message consumption have been realized , But what we want to achieve is a queue that can consume messages automatically , So the idea is , We're going to start the project , Put the consumer in a state of readiness , After the provider sends the message , Consumers can consume in real time .
package com.dm.black.modules.myQuere;
import java.util.LinkedList;
/**
* consumer
* @author wjy
* @date 2021/1/20
*/
public class MConsumer {
private final String queueName = "demo";
/**
* Receive messages and delete
*/
public void receiveMessageAndDelete() {
MQueue queue = QueueCenter.getQueue(queueName);
// If there are messages in the queue , They are always in a state of consumption
while (true) {
// News consumption , Delete after performing a lot of business processing
Object o = queue.pollFirst();
System.out.println(" consumer :" + queueName + ": Message received :" + o.toString());
}
}
} 

How to make consumers consume information at any time ? The answer is at the start of the project , Just initialize the consumer , Let consumers monitor messages in real time . 
package com.dm.black;
import com.dm.black.modules.myQuere.MConsumer;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.dm.black.modules.*.mapper")
@SpringBootApplication
public class BlackApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(BlackApplication.class, args);
}
@Override
public void run(String... strings) throws Exception {
// Start consumer
MConsumer mConsumer = new MConsumer();
mConsumer.receiveMessageAndDelete();
}
} 

test

We offer a controller To register messages
package com.dm.black.modules.myQuere;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author wjy
* @date 2021/1/22
*/
@RestController
@RequestMapping("/mQueue")
public class MQueueController {
@GetMapping("/sendMessage")
public String sendMessage(String message) {
MProvider mProvider = new MProvider();
mProvider.sendMessage(message);
return "success";
}
} 

We see , When the project starts , The consumer is ready , No messages in queue , So it's blocked , When the supervisor hears the news , Work and consume right away .

Let's call

Take a look at the console output

You can see , The first time the provider registers a message , Wake up the queue , And register in the queue , The consumer is listening to the news , Start working right away .

So far, we have implemented a simple version of message queuing , If it's helpful , Hope to support more .

Because there is no new project to do this Demo, So we don't provide the source code , Let's do it ourselves copy Let me post the code

版权声明
本文为[Kind little black brother]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210122154416191I.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云