redis[1]客户端简单样例

为了更加深入的理解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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值