六 工作佇列

2022-09-02 21:36:21 字數 1736 閱讀 9243

工作佇列,用於多個消費者從佇列中消費多個訊息。

工作佇列(又稱:任務佇列)背後的主要思想是避免立即執行資源密集型任務,並且必須等待它完成。相反,我們安排任務稍後完成。我們將任務封裝 為訊息並將其傳送到佇列。在後台執行的工作程序將彈出任務並最終執行作業。當您執行許多任務作程式時,它們之間將共享任務。

這個概念在web應用程式中特別有用,因為在短的http請求視窗中無法處理複雜的任務。

生產者傳送訊息:

/**

* @author hayson

* @date 2018/11/23 13:39

* @description rabbitmq生產者傳送多條訊息

*/public class send

public static void send() throws ioexception, timeoutexception

channel.close();

connection.close();}}

消費者接收訊息1:

/**

* @author hayson

* @date 2018/11/23 13:41

* @description rabbitmq消費者接收訊息1

*/public class receiver2

public static void recevier() throws ioexception, timeoutexception

};channel.basicconsume(queue, true, consumer);}}

消費者接收訊息2:

/**

* @author hayson

* @date 2018/11/23 13:41

* @description rabbitmq消費者接收訊息2

*/public class receiver2

public static void recevier() throws ioexception, timeoutexception

};channel.basicconsume(queue, true, consumer);}}

先啟動上面兩個消費者客戶端監聽佇列訊息,後啟動生產者傳送訊息,結果如下:

生產者:

傳送訊息:hello world! 0

傳送訊息:hello world! 1

傳送訊息:hello world! 2

傳送訊息:hello world! 3

傳送訊息:hello world! 4

消費者1:

接收到訊息:hello world! 0

接收到訊息:hello world! 2

接收到訊息:hello world! 4

消費者2:

接收到訊息:hello world! 1

接收到訊息:hello world! 3

可以看到,rabbitmq將按順序將每條訊息傳送給下乙個消費者。平均而言,每個消費者將獲得相同數量的訊息。這種分發訊息的方式稱為輪詢法。上面還可以傳送更多的訊息和新增更多的消費者監聽佇列。

工作佇列分析

一 用法 struct cpu workqueue struct cacheline aligned the externally visible workqueue abstraction is an array of per cpu workqueues struct workqueue str...

工作佇列模型

workqueue,中文稱其為工作佇列,是乙個用於建立核心執行緒的介面,通過它建立的核心執行緒來執行核心其他模組排列到佇列裡的工作,建立的核心執行緒被稱為工作者執行緒。要理解工作佇列的實現,重點在於理解相關的三個資料結構的含義及關係。1 表示工作佇列型別的資料結構 struct workqueue ...

工作佇列分析

一 用法 struct cpu workqueue struct cacheline aligned the externally visible workqueue abstraction is an array of per cpu workqueues struct workqueue str...