項目開發中免不了各模塊或系統之間進行消息通訊,目前熱門的消息中間件有Redis、RabbitMQ、Kafka、RocketMQ等等。html
以上幾種組件中Redis在消息隊列方面表現還能夠,可是若是涉及發佈訂閱功能,就不行了,最近項目就使用了redis的發佈訂閱,前端
每秒只能發出幾千條,雖然目前綽綽有餘,可是瓶頸能夠預期。程序員
其他的幾種都是比較重量級的消息中間件,什麼跨平臺、分佈式、集羣、支持N種協議等等,很高大全,web
咱們可能就只使用了其中一、2個功能。嚴格來講,項目中集成這幾種MQ的工做量是不小的,對於中小型系統來講,可能維護MQredis
穩定的工做量都比項目還大,難度也高,全部功能用全了的程序員恐怕很少。數組
從長遠考慮出發,選擇重量級MQ恐怕是板上釘釘的事,可是項目一開始就上這幾種,我以爲那也是欠缺考慮的。若是項目app
根本不要求跨機器通訊,那殺雞就不要用牛刀了。好比,你只是在模塊之間、線程之間、進程之間,或者是在同一主機的各類不一樣系統之間,分佈式
其實均可以不用重量級MQ。固然你使用了也沒事,看我的選擇。ide
最近的項目有這麼個場景,採集近全部底層設備,每一個設備有點3000個,總共20多萬個點須要採集上來。剛開始使用了Redis的發佈訂閱,函數
可是程序毫無疑問地掛了,根本帶不起來;由於程序啓動時每一個點的值都是從0變成N,就須要發消息出來,那一開始消息是不少的,redis根本
處理不完,並且有很高頻率的超時斷線。以致於想換RabbitMQ,後來想一想仍是算了,由於那樣增長項目難度不說,後期維護也是個難題。
說到底這是模塊之間的通訊,是主程序(Winform)調用採集C++的DLL類庫,發出消息後主程序和web端訂閱,在主程序與DLL這邊,在DLL
方法上增長一個回調函數就搞定了,徹底不用走消息中間件,Web端要哪些點的實時值就先ASK,先請求須要看哪些點,如何在主程序這邊
發佈那些點的實時值消息,這樣發佈訂閱的數據量少了二、3個數量級不止。
針對上邊的業務場景,由於是模塊之間的線程間通訊,這樣搞問題不大;若是是進程之間也要那麼高頻率的通訊,那就很差辦了,咱們
不想使用重量級MQ,又想高頻率傳輸消息,怎麼辦呢?網上搜索了一番,貌似沒看到有成熟的速度又快、體量又小,部署又簡單的中間件。
因此在下不才,針對這個問題拋磚引玉,作一個demo出來供你們討論一下。
應題,就是使用內存映射來作同一個機器下各類消息的通訊,以前也寫過一篇關於使用共享內存實現快速讀寫的文章,點擊前往瀏覽
「.net環境下跨進程、高頻率讀寫數據」,可是內存映射比較適合作消息隊列,由於消息能夠持久化在本地,沒讀完下次進來還能夠接着讀。
我預想是這樣設計:
一、發佈訂閱涉及到2個主要方法:Publish(string channel)、Subscribe(string channel, Callback callback);
二、爲每一個channel生成一個文件:channel.db,默認每一個db能夠存儲1000個同類型的結構體消息做爲消息隊列,從頭部寫入,尾部讀出。
每一個db文件前面留一個索引區做爲發佈方與訂閱方各自的讀寫位置。發佈與訂閱前,先讀寫這個索引區,由於是一對一讀寫,因此
能夠完美避開讀寫鎖,大大提升性能。
三、針對一對多需求,單獨設計一個config.db文件存儲種channel與其相關訂閱信息,大概原理圖以下:
四、解決讀寫不加鎖問題
咱們看結構體:SIndex有三個屬性
1) WriteIndex 記錄發佈方(Pubish)最後寫入數據的位置
2) ReadIndex 記錄訂閱方(Subscribe)最後讀取數據的位置
3) Over 表示WriteIndex已達到隊列最大值,再WriteIndex小於等於隊列最大值前,讀寫以下圖:
WriteIndex達到最大值後再往下寫Over就要取反,如由False變爲True。WriteIndex=0
若是此時沒有訂閱方,那新消息就會被拋棄,由於已無空間存儲。
4) 若是ReadIndex數值到隊列最大值,Over也取反,此時ReadIndex = 0,讀寫又變成圖1所示
5) 讀寫過程當中並不存在互斥的狀況,只要管理好讀寫位置,就能夠避免加鎖。
4.一、主要參數定義
#define FM_MAX_CHANNEL 100 // 暫定最多100個不一樣頻道 #define FM_MAX_SUBSCRIBE 3 // 暫定最多3個訂閱用戶 #define FM_MAX_ROWS 1000 // 暫定最多隊列大小爲1000 #define FM_DISCONNECT_TIME 5000 // 超過5000毫秒無意跳更新視爲訂閱斷開 #define FM_KEEP_CONN_CYCLE 1000 // 保持心跳鏈接的時間週期 #define FM_NOTHING -1 // 空白,數組爲0等 #define FM_WORD_SIZE sizeof(WORD) // WORD長度 #define FM_INDEX_SIZE sizeof(SIndex) // SIndex長度
4.二、結構體
1 // 索引 2 typedef struct 3 { 4 WORD WriteIndex; 5 WORD ReadIndex; 6 WORD Over; // 當W或R超過MAX一次,Over取反一次,Over默認爲False 7 }SIndex; 8 9 // 內存映射參數 10 typedef struct 11 { 12 HANDLE FileHandle; 13 HANDLE FileMappingHandle; 14 LPVOID MapViewOfFileHandle; 15 UINT StructSize; 16 char FileName[20]; 17 UINT SubscribeIndex; 18 WORD Conned; 19 }SDbConnInfo; 20 21 // 頻道 22 typedef struct 23 { 24 char ChannelName[20]; 25 UINT StructSize; 26 DWORD Subscribe1LastTime; 27 DWORD Subscribe2LastTime; 28 DWORD Subscribe3LastTime; 29 }SChannel; 30 31 // 頻道與訂閱映射 32 typedef struct 33 { 34 char ChannelName[20]; 35 SDbConnInfo DbConnInfo[FM_MAX_SUBSCRIBE]; 36 }SChannelMapDbConnInfo;
4.三、主要方法
// 發佈信息 template<typename T> int Publish(const char *channel, T* data); // 訂閱信息 template<typename T> void Subscribe(const char *channel, SubscribeCallBackHandle callback);
5.1 、FMDBManager,主要管理內存映射相關操做,由於是讀寫位置不同,因此不須要加互斥量
1 class FMDBManager 2 { 3 public: 4 FMDBManager() {}; 5 ~FMDBManager() {}; 6 7 public: 8 static int Create(SDbConnInfo *info) 9 { 10 CString fileName(info->FileName); 11 DWORD totalSize = (FM_MAX_ROWS * info->StructSize) + FM_INDEX_SIZE; 12 13 info->FileHandle = CreateFile(fileName, (GENERIC_READ | GENERIC_WRITE), (FILE_SHARE_READ | FILE_SHARE_WRITE), 14 NULL, OPEN_ALWAYS, FILE_FLAG_SEQUENTIAL_SCAN, NULL); 15 16 info->FileMappingHandle = CreateFileMapping(info->FileHandle, NULL, PAGE_READWRITE, 0, totalSize, NULL); 17 18 if(info->FileMappingHandle == NULL || info->FileMappingHandle == INVALID_HANDLE_VALUE) 19 { 20 Log(""); 21 CloseHandle(info->FileHandle); 22 return enumFail; 23 } 24 25 if(GetLastError() == ERROR_ALREADY_EXISTS) 26 { 27 Log(""); 28 return enumFail; 29 } 30 31 // init 32 info->MapViewOfFileHandle = MapViewOfFile(info->FileMappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, totalSize); 33 34 if(info->MapViewOfFileHandle == NULL) 35 { 36 Log(""); 37 CloseHandle(info->FileMappingHandle); 38 CloseHandle(info->FileHandle); 39 return enumFail; 40 } 41 42 return enumSuccess; 43 } 44 45 protected: 46 int Write(void *data, UINT order, SDbConnInfo *info) 47 { 48 if(info->MapViewOfFileHandle == NULL) 49 { 50 Log(""); 51 return enumFail; 52 } 53 else 54 memcpy((char *)info->MapViewOfFileHandle + (order * info->StructSize) + FM_INDEX_SIZE, data, info->StructSize); 55 56 return enumSuccess; 57 } 58 int Read(void *data, UINT order, SDbConnInfo *info) 59 { 60 if(info->MapViewOfFileHandle == NULL) 61 { 62 Log(""); 63 return enumFail; 64 } 65 else 66 memcpy(data, (char *)info->MapViewOfFileHandle + (order * info->StructSize) + FM_INDEX_SIZE, info->StructSize); 67 68 return enumSuccess; 69 } 70 int Delete(UINT order, SDbConnInfo *info) 71 { 72 if(info->MapViewOfFileHandle == NULL) 73 { 74 Log(""); 75 return enumFail; 76 } 77 else 78 memset((char *)info->MapViewOfFileHandle + (order * info->StructSize) + FM_INDEX_SIZE, 0, info->StructSize); 79 80 return enumSuccess; 81 } 82 83 int WriteConfig(void *data, UINT order, UINT pos, UINT size, SDbConnInfo *info) 84 { 85 if(info->MapViewOfFileHandle == NULL) 86 { 87 Log(""); 88 return enumFail; 89 } 90 else 91 memcpy((char *)info->MapViewOfFileHandle + (order * info->StructSize) + FM_INDEX_SIZE + pos, data, size); 92 93 return enumSuccess; 94 } 95 int WriteIndex(void *data, UINT pos, UINT size, SDbConnInfo *info) 96 { 97 if(info->MapViewOfFileHandle == NULL) 98 { 99 Log(""); 100 return enumFail; 101 } 102 else 103 memcpy((char *)info->MapViewOfFileHandle + pos, data, size); 104 105 return enumSuccess; 106 } 107 int ReadIndex(SIndex *sIndex, SDbConnInfo *info) 108 { 109 if(info->MapViewOfFileHandle == NULL) 110 { 111 Log(""); 112 return enumFail; 113 } 114 else 115 memcpy(sIndex, (char *)info->MapViewOfFileHandle, FM_INDEX_SIZE); 116 117 return enumSuccess; 118 } 119 };
5.二、FMDBClient,內存映射客戶端,主要封裝Publish與Subscribe方法給前端調用,屏蔽複雜性
1 class FMDBClient : public FMDBManager 2 { 3 private: 4 mutable std::mutex mut; 5 SChannelMapDbConnInfo channelMapDbConnInfo = { 0 }; 6 7 bool CanWrite(SIndex *sIndex) 8 { 9 int nextWriteIndex = sIndex->WriteIndex + 1; 10 if(nextWriteIndex > FM_MAX_ROWS) nextWriteIndex = 0; 11 12 return nextWriteIndex != sIndex->ReadIndex; 13 } 14 bool CanRead(SIndex *sIndex) { 15 if(sIndex->Over) return sIndex->ReadIndex > sIndex->WriteIndex; 16 else return sIndex->ReadIndex + 1 <= sIndex->WriteIndex; 17 } 18 19 int GetDbConnInfo(const char *channel, int size) 20 { 21 int rest = enumFail; 22 23 for(int i = 0; i < FM_MAX_CHANNEL; i++) 24 { 25 char channelNameTmp[20] = { 0 }; 26 sprintf_s(channelNameTmp, "%s", channel); 27 28 if(0 == strcmp(channelNameTmp, channelMapDbConnInfoArray[i].ChannelName)) 29 { 30 channelMapDbConnInfo = channelMapDbConnInfoArray[i]; 31 rest = enumSuccess; 32 break; 33 } 34 } 35 36 return rest; 37 } 38 int SetDbConnInfo(const char *channel, UINT *subscribeIndex, SDbConnInfo *dbConnInfo) 39 { 40 std::lock_guard<std::mutex> lk(mut); 41 42 int nextSubscribeIndex = fmdbConfig->GetNextSubscribeIndex(channel); 43 if(nextSubscribeIndex == FM_NOTHING) 44 { 45 SChannel sChannel = { 0 }; 46 sprintf_s(sChannel.ChannelName, "%s", channel); 47 sChannel.Subscribe1LastTime = GetTickCount(); 48 sChannel.StructSize = dbConnInfo->StructSize; 49 50 sprintf_s(dbConnInfo->FileName, "%s.1.db", channel); 51 if(!fmdbConfig->IsFM_NOTHING(dbConnInfo->FileName) && dbConnInfo->StructSize > 0) 52 { 53 dbConnInfo->SubscribeIndex = 1; 54 *subscribeIndex = dbConnInfo->SubscribeIndex; 55 56 if(Create(dbConnInfo) == enumSuccess) return fmdbConfig->Insert(&sChannel); 57 else sprintf_s(dbConnInfo->FileName, "%s", channel); //還原名稱 58 } 59 } 60 61 if(nextSubscribeIndex > 1) 62 { 63 sprintf_s(dbConnInfo->FileName, "%s.%d.db", channel, nextSubscribeIndex); 64 if(!fmdbConfig->IsFM_NOTHING(dbConnInfo->FileName) && dbConnInfo->StructSize > 0) 65 { 66 dbConnInfo->SubscribeIndex = nextSubscribeIndex; 67 *subscribeIndex = nextSubscribeIndex; 68 69 if(Create(dbConnInfo) == enumSuccess) return fmdbConfig->Save(channel, nextSubscribeIndex); 70 else sprintf_s(dbConnInfo->FileName, "%s", channel); //還原名稱 71 } 72 } 73 74 return enumFail; 75 } 76 bool SetSubscribeConned(const char *channel, int subscribeIndex, SDbConnInfo *dbConnInfo) 77 { 78 int rest = enumFail; 79 80 if(subscribeIndex <= 0) return rest; 81 82 for(int i = 0; i < FM_MAX_CHANNEL; i++) 83 { 84 char channelNameTmp[20] = { 0 }; 85 sprintf_s(channelNameTmp, "%s", channel); 86 87 if(0 == strcmp(channelNameTmp, channelMapDbConnInfoArray[i].ChannelName)) 88 { 89 channelMapDbConnInfoArray[i].DbConnInfo[subscribeIndex - 1].SubscribeIndex = dbConnInfo->SubscribeIndex; 90 channelMapDbConnInfoArray[i].DbConnInfo[subscribeIndex - 1].Conned = 1; 91 rest = enumSuccess; 92 break; 93 } 94 } 95 96 return rest; 97 } 98 bool IsConning(SDbConnInfo *dbConnInfo) { return true; }; 99 100 public: 101 FMDBClient() 102 { 103 while(!fmdbConfigLoadFinish) { Sleep(200); } 104 }; 105 ~FMDBClient() {}; 106 107 public: 108 int failTimes = 0; 109 110 template<typename T> 111 int Publish(const char *channel, T* data) 112 { 113 int rest = enumFail; 114 115 // 查找 116 if(GetDbConnInfo(channel, sizeof(T)) == enumFail) 117 { 118 printf_s("發佈%s失敗.\n", channel); 119 return enumFail; 120 } 121 122 for(int i = 0; i < FM_MAX_SUBSCRIBE; i++) 123 { 124 if(channelMapDbConnInfo.DbConnInfo[i].FileHandle == NULL) continue; 125 126 while(IsConning(&channelMapDbConnInfo.DbConnInfo[i])) 127 { 128 SIndex sIndex = { 0 }; 129 if(ReadIndex(&sIndex, &channelMapDbConnInfo.DbConnInfo[i]) == enumFail) 130 { 131 throw "映射文件加載失敗"; 132 } 133 134 if(CanWrite(&sIndex)) 135 { 136 WORD writeIndex = sIndex.WriteIndex; 137 if(Write(data, writeIndex, &channelMapDbConnInfo.DbConnInfo[i]) == enumSuccess) 138 { 139 writeIndex++; 140 if(writeIndex > FM_MAX_ROWS) 141 { 142 writeIndex = 0; 143 144 WORD Over = TRUE; 145 WriteIndex(&Over, (FM_WORD_SIZE * 2), FM_WORD_SIZE, &channelMapDbConnInfo.DbConnInfo[i]); 146 } 147 148 rest = WriteIndex(&writeIndex, 0, FM_WORD_SIZE, &channelMapDbConnInfo.DbConnInfo[i]); 149 break; 150 } 151 } 152 else 153 { 154 failTimes++; 155 } 156 } 157 } 158 159 return rest; 160 } 161 162 template<typename T> 163 void Subscribe(const char *channel, SubscribeCallBackHandle callback) 164 { 165 SDbConnInfo dbConnInfo = { 0 }; 166 dbConnInfo.StructSize = sizeof(T); 167 168 UINT subscribeIndex = 0; 169 if(SetDbConnInfo(channel, &subscribeIndex, &dbConnInfo) == enumFail) 170 { 171 printf_s("訂閱%s失敗.\n", channel); 172 return; 173 } 174 175 while(IsConning(&dbConnInfo)) 176 { 177 SetSubscribeConned(channel, subscribeIndex, &dbConnInfo); 178 179 SIndex sIndex = { 0 }; 180 if(ReadIndex(&sIndex, &dbConnInfo) == enumFail) throw "映射文件加載失敗"; 181 if(!CanRead(&sIndex)) continue; 182 183 T t = { 0 }; 184 int readIndex = sIndex.ReadIndex; 185 if(Read(&t, readIndex, &dbConnInfo) == enumSuccess) 186 { 187 readIndex++; 188 if(readIndex > FM_MAX_ROWS) 189 { 190 readIndex = 0; 191 192 WORD Over = FALSE; 193 WriteIndex(&Over, (FM_WORD_SIZE * 2), FM_WORD_SIZE, &dbConnInfo); 194 } 195 196 if(WriteIndex(&readIndex, FM_WORD_SIZE, FM_WORD_SIZE, &dbConnInfo) == enumSuccess) 197 if(Delete(sIndex.ReadIndex, &dbConnInfo) == enumSuccess) 198 if(callback(&t) == enumBreak) break; 199 } 200 } 201 } 202 };
請注意上邊控制讀寫的2個方法
bool CanWrite(SIndex *sIndex) { int nextWriteIndex = sIndex->WriteIndex + 1; if(nextWriteIndex > FM_MAX_ROWS) nextWriteIndex = 0; return nextWriteIndex != sIndex->ReadIndex; } bool CanRead(SIndex *sIndex) { if(sIndex->Over) return sIndex->ReadIndex > sIndex->WriteIndex; else return sIndex->ReadIndex + 1 <= sIndex->WriteIndex; }
咱們能夠分析一下,下一個WriteIndex值若是大於隊列最大值 WriteIndex置0,下一個WriteIndex數值若是不等於
正在讀的位置ReadIndex就能寫;若是WriteIndex沒有超出最大值,只要ReadIndex小於等於WriteIndex就能讀,
若是超出,就判斷ReadIndex大於WriteIndex就能讀。WriteIndex與ReadIndex數值在Publish與Subscribe中維護
5.三、創建新線程獲取最新訂閱的客戶端信息,這個功能主要是動態地像多個Subscribe端發生消息,好比訂閱發生在發佈以後,
也應該能收到消息。
1 void Update() 2 { 3 while(true) 4 { 5 if(fmdbConfig->GetChannelArray() == enumSuccess) 6 { 7 for(int i = 0; i < FM_MAX_CHANNEL; i++) 8 { 9 if(fmdbConfig->IsFM_NOTHING(channelMapDbConnInfoArray[i].ChannelName)) continue; 10 11 for(int j = 0; j < FM_MAX_SUBSCRIBE; j++) 12 { 13 if(channelMapDbConnInfoArray[i].DbConnInfo[j].StructSize <= 0) continue; 14 15 // KeepConned 16 if(channelMapDbConnInfoArray[i].DbConnInfo[j].Conned) 17 { 18 fmdbConfig->KeepConned(channelMapDbConnInfoArray[i].ChannelName, 19 channelMapDbConnInfoArray[i].DbConnInfo[j].SubscribeIndex); 20 21 channelMapDbConnInfoArray[i].DbConnInfo[j].Conned = 0; 22 //printf_s("%s.KeepConned.\n", channelDbParsArray[i].SDbPars[j].Channel); 23 } 24 25 if(!fmdbConfig->Exists(channelMapDbConnInfoArray[i].DbConnInfo[j].FileName)) 26 { 27 FMDBManager::Create(&channelMapDbConnInfoArray[i].DbConnInfo[j]); 28 fmdbConfig->AddChannel(channelMapDbConnInfoArray[i].DbConnInfo[j].FileName); 29 } 30 } 31 } 32 } 33 34 fmdbConfigLoadFinish = true; 35 Sleep(1000); 36 } 37 } 38 thread th(Update);
6.一、Producer.cpp
1 #include "pch.h" 2 #include "../FMDB.h" 3 4 using namespace std; 5 6 int main() 7 { 8 FMClient * client = new FMClient(); 9 10 int times = 0; 11 int index = 0; 12 int total = 0; 13 UINT structSize = sizeof(SPerson); 14 DWORD dwStartTmp = GetTickCount(); 15 16 while(TRUE) 17 { 18 times++; 19 if(index == 0) 20 { 21 dwStartTmp = GetTickCount(); 22 } 23 24 SPerson sPerson = { 0 }; 25 sPerson.Idx = index; 26 sprintf_s(sPerson.Name, "Name.%d", index); 27 sPerson.Age = index; 28 29 if(client->Publish("Person", &sPerson) == enumSuccess) 30 { 31 if(index % 2 == 0) total = total + sPerson.Idx; 32 else total = total - sPerson.Idx; 33 34 index++; 35 if(index % 50000 == 0) 36 printf_s("發送條數: %d, 耗時:%d \n", index, (GetTickCount() - dwStartTmp)); 37 } 38 39 if(index >= 2000000) break; 40 } 41 42 printf_s("調用次數: %d, 成功條數: %d, 檢驗值: %d \n", times, index, total); 43 system("pause"); 44 }
6.二、Consumer.cpp
1 #include "pch.h" 2 #include "../FMDB.h" 3 4 using namespace std; 5 6 int index = 0; 7 int total = 0; 8 DWORD dwStartTmp = GetTickCount(); 9 10 int SubscribeCallback(void *msg) 11 { 12 SPerson * person = (SPerson *)msg; 13 14 if(index == 0) 15 { 16 dwStartTmp = GetTickCount(); 17 } 18 19 if(index % 2 == 0) total = total + person->Idx; 20 else total = total - person->Idx; 21 22 index++; 23 if(index % 50000 == 0) 24 { 25 printf("接收條數: %d, 耗時:%d, Idx:%d, Name:%s, Age:%d\n", 26 index, (GetTickCount() - dwStartTmp), person->Idx, person->Name, person->Age); 27 } 28 29 if(index >= 2000000) 30 { 31 return enumBreak; 32 } 33 34 return enumSuccess; 35 }; 36 37 int main() 38 { 39 FMClient * client = new FMClient(); 40 client->Subscribe<SPerson>("Person", SubscribeCallback); 41 42 printf("接收條數: %d, 檢驗值: %d \n", index, total); 43 system("pause"); 44 }
6.三、運行,測試用例中使用了向隊列發送200萬條數據,消息大小128字節,訂閱端也是接受到200萬數據後退出,而且打印檢驗值。
1) 檢驗值計算:0+1-2+3-4+ --------- - 2000000 = -1000000,若是隊列運行正常,那兩邊的檢驗值應該都是是 -1000000.
2) 每5萬條打印一第二天志,運行狀況以下
一對一方式運行三次,分別耗時(毫秒):288六、297九、2871
3) 一對二方式運行三次,分別耗時(毫秒):408七、400九、4040
4)運行過程當中產生的文件
6.四、200萬數據一對一耗時近3秒,貌似也不是很是快是否是?可是這就是最大速度了嗎?
固然不是哦,別忘了這是debug版本,咱們切換到release版本看速度會不會有所提高。
一對一運行三次耗時分別是:122四、137三、1326
厲害了,
SPerson結構體128字節,每秒能夠處理180萬數據,固然實際運用確定達不到,由於處理其餘業務邏輯也要耗時間。
好了,爲了這個demo腦袋都想疼了,思考模型,調試BUG,期間各類問題,實在茶壺煮餃子,有苦說不出。
你看,又浪費我週末2天時間,期間就吃了一餐,今天的還沒吃呢,等下去旁邊山上走走,否則就要發黴了。拜拜。。。