redis 源码学习记录

终于有时间来分析redis源码了。

在github上找了一个循序渐进学习redis的实例库。第一部分就是学习redis的网络模型。之前研究skynet模型时有深入的学习网络模型,所以看这块还算轻松。网上有各种剖析redis网络模型的blog,我这里就不再班门弄斧了,仅仅记录学习的过程。

令人惊奇的是,redis网络模型居然是单线程的,处理网络IO和事件回调处理竟然在同一个线程里面。skynet和muduo都是主线程处理网络IO,工作线程处理回调事件。我觉得这种模型才比较合理吧,万一事件回调的处理时间很长,那不是会阻碍网络IO的处理吗?不过大家都说redis高并发的能力毋庸置疑了,还是不太相信单线程能担当起这个重任,这点请大佬赐教。

参考资料:

https://github.com/linyiqun/Redis-Code

https://blog.csdn.net/Androidlushangderen/article/details/40474815

https://www.cnblogs.com/shijingxiang/articles/5369224.html

https://www.cnblogs.com/daoluanxiaozi/p/3590093.html


学习redis网络模型时的代码如下:

#include "ae.h"

#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <sys/time.h>

#define MAXFD 5

void loop_init(struct aeEventLoop* l) {
	printf("I am loop_init !!!\n");
}

void file_cb(struct aeEventLoop* l, int fd, void* data, int mask)  {
	char buf[51] = {0};
	read(fd, buf, 51);
	printf("I am file_cb, here [EventLoop : %p], [fd ;%d], [data : %s, [mask ; %d]\n", l, fd, data, mask);
	printf("get %s \n", buf);
}

int time_cb(struct aeEventLoop* l, long long id, void* data)  {
	printf("now is %ld,\n", time(NULL));
	printf("I am time_cb, here [EventLoop : %p], [fd ;%d], [data : %p]\n", l, id, data);
	return 5 * 1000;
}


void fin_cb(struct aeEventLoop* l, void* data)  {
	puts("call the unknow final funciton \n");
}

int main(int argc, char const *argv[])
{
	aeEventLoop* l;
	char * msg = "here std say:";
	char * user_data = malloc(50 * sizeof(char));
	if (! user_data)  {
		assert(("user_data malloc error", user_data));
	}
	memset(user_data, 0, 50);
	memcpy(user_data, msg, strlen(msg));
	l = aeCreateEventLoop(MAXFD);
	aeSetBeforeSleepProc(l, loop_init);
	int res = aeCreateFileEvent(l, STDIN_FILENO, AE_READABLE, file_cb, user_data);
	printf("create file event is ok ? [%d]\n", res);
	res = aeCreateTimeEvent(l, 5 * 1000, time_cb, NULL, fin_cb);
	printf("create time event is ok? [%d]\n", res);
	aeMain(l);
	puts("every thing is ok!!! \n");
	return 0;
}


扫描二维码关注公众号,回复: 1796507 查看本文章

猜你喜欢

转载自blog.csdn.net/zxm342698145/article/details/80697953