最近開始在kendynet上開發手游服務端,游戲類型是生存挑戰類的,要存儲的數據結構和類型都比較簡單,於是選擇了用redis做存儲,數據類型使用string基本就足夠了。於是在kendynet上寫了一個簡單的redis異步訪問接口.
1.項目時間緊迫,不打算提供一個大而全的訪問接口,只提供一個request接口用以發出redis請求.
2.數據在redis中key和value都存儲為string,由使用者負責將數據序列化成string,從string反序列化回數據.
3.服務支持本地訪問和遠程訪問,服務自動根據請求發起的位置將結果返回給請求者.
4.數據庫操作結果通過異步消息返回給調用者.
下面先看一個使用示例:
#include <stdio.h> #include <stdlib.h> #include "core/msgdisp.h" #include <stdint.h> #include "testcommon.h" #include "core/db/asyndb.h" asyndb_t asydb; int g = 0; int count = 0; void db_setcallback(struct db_result *result); void db_getcallback(struct db_result *result) { //printf("%s\n",result->result_str); count++; char req[256]; snprintf(req,256,"set key%d %d",g,g); if(0 != asydb->request(asydb,new_dbrequest(db_set,req,db_setcallback,result->ud,make_by_msgdisp((msgdisp_t)result->ud)))) printf("request error\n"); } void db_setcallback(struct db_result *result) { if(result->ud == NULL) printf("error\n"); char req[256]; snprintf(req,256,"get key%d",g); g = (g+1)%102400; asydb->request(asydb,new_dbrequest(db_get,req,db_getcallback,result->ud,make_by_msgdisp((msgdisp_t)result->ud))); } int32_t asynprocesspacket(msgdisp_t disp,msgsender sender,rpacket_t rpk) { uint16_t cmd = rpk_read_uint16(rpk); if(cmd == CMD_DB_RESULT) { struct db_result *result = rpk_read_dbresult(rpk); result->callback(result); free_dbresult(result); } return 1; } static void *service_main(void *ud){ msgdisp_t disp = (msgdisp_t)ud; while(!stop){ msg_loop(disp,50); } return NULL; } int main(int argc,char **argv) { setup_signal_handler(); msgdisp_t disp1 = new_msgdisp(NULL, NULL, NULL, NULL, asynprocesspacket, NULL); thread_t service1 = create_thread(THREAD_JOINABLE); msgdisp_t disp2 = new_msgdisp(NULL, NULL, NULL, NULL, asynprocesspacket, NULL); thread_t service2 = create_thread(THREAD_JOINABLE); asydb = new_asyndb(); asydb->connectdb(asydb,"127.0.0.1",6379); asydb->connectdb(asydb,"127.0.0.1",6379); //發出第一個請求uu char req[256]; snprintf(req,256,"set key%d %d",g,g); asydb->request(asydb,new_dbrequest(db_set,req,db_setcallback,disp1,make_by_msgdisp(disp1))); thread_start_run(service1,service_main,(void*)disp1); asydb->request(asydb,new_dbrequest(db_set,req,db_setcallback,disp2,make_by_msgdisp(disp2))); thread_start_run(service2,service_main,(void*)disp2); uint32_t tick,now; tick = now = GetSystemMs(); while(!stop){ sleepms(100); now = GetSystemMs(); if(now - tick > 1000) { printf("count:%d\n",count); tick = now; count = 0; } } thread_join(service1); thread_join(service2); return 0; }
上面的示例程序創建了一個redis異步處理器,然後建立了兩個到同一個redis服務器的連接,在實現中,每個連接都會創建一個工作線程,用以完成數據庫請求.這些工作線程會共享一個任務隊列,使用者發出的請求被投遞到任務隊列中,由工作線程提取並執行.
之後創建兩個消息分離器和兩個線程,然後發起兩個set請求和啟動消息分離器線程.
當set返回後,由消息分離器回調db_setcallback,在db_setcallback中繼續發起一個get請求,
在get的回調db_getcallback繼續發起新的set請求,如此反復.