redis[1]客户端简单样例

来源:互联网 发布:监狱建筑师 for mac 编辑:程序博客网 时间:2024/05/21 07:00

为了更加深入的理解redis通讯协议,写了一个简单的客户端,
注意:官方提供了客户端,一般情况下直接用官方的就可以了

以下代码采用最简单的select模型,并且没有做异常处理;
程序逻辑比较简单测试测试了下不同线程数情况下 不同写入通一个key值情况的性能

#include <stdio.h>#include <stddef.h>#include <stdint.h>#include <thread>#include <atomic>#include <winsock2.h>#pragma comment(lib, "ws2_32.lib")int g_time_out_s = 30;size_t read(SOCKET fd, char *buf, size_t count){    struct timeval timeout;    timeout.tv_sec = g_time_out_s;    timeout.tv_usec = 0;    fd_set readfds;    FD_ZERO(&readfds);    FD_SET(fd, &readfds);       int num = select(0, &readfds, NULL, NULL, &timeout);    if (num > 0)    {        return recv(fd, buf, count, 0);    }    printf("读取异常\n");    return num;}size_t write(SOCKET fd, char *buf, size_t count){    struct timeval timeout;    timeout.tv_sec = g_time_out_s;    timeout.tv_usec = 0;    fd_set writefds;    FD_ZERO(&writefds);    FD_SET(fd, &writefds);    int num = select(0, NULL, &writefds, NULL, &timeout);    if (num > 0)    {        return send(fd, buf, count, 0);    }    printf("写入异常\n");    return num;}int g_MAX = 100000;int test(){    SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);    if (s == INVALID_SOCKET)        return 0;    int port = 10000;    char *ip = "192.168.120.211";    SOCKADDR_IN addr;    addr.sin_family = AF_INET;    addr.sin_port = htons(port);    addr.sin_addr.S_un.S_addr = inet_addr(ip);    int code = connect(s, (struct sockaddr FAR *) &addr, sizeof(addr));    if (code != 0)        return 0;    for (int i = 0; i < g_MAX; ++i)    {        char write_buf[1024] = { 0 };        char read_buf[1024] = { 0 };        strcpy(write_buf, "*3\x0d\x0a$3\x0d\x0aset\x0d\x0a$3\x0d\x0amsg\x0d\x0a$5\x0d\x0ahello\x0d\x0a");        write(s, write_buf, strlen(write_buf));         read(s, read_buf, sizeof(read_buf));            }    return 0;}int main(int argc, char **argv){    WSADATA wsaData;    WSAStartup(MAKEWORD(2, 2), &wsaData);   #define THRS 300    std::thread thr_pool[THRS];    for (int thrs = 1; thrs <= THRS; ++thrs)    {        long long b_time = GetCurrentTime();        for (int i = 0; i < thrs; ++i)        {            std::thread thr_temp(test);            thr_pool[i].swap(thr_temp);        }        for (int i = 0; i < thrs; ++i)            thr_pool[i].join();        long long e_time = GetCurrentTime();        printf("[%2d]个线程下 速度:%f (笔/s)\n", thrs, (1000.0 * g_MAX * thrs) / (e_time - b_time));    }           system("pause");    return 0;}

截图是程序跑的部分结果

同步执行set命令

0 0