您的位置:首页 > 数据库 > Memcache

memcache -- php的memcached客户端程序源码学习

2008-11-19 17:22 716 查看
入口程序是在memcache.c中,提供了connect,set,get,add,replace等功能。

1、数据结构

很重要的一个.c文件是memcache_pool.c,提供了连接池的功能,还有很多的读写函数。首先看它对应的memcache_pool.h,其中定义了一些重要的数据结构:
struct mmc_buffer, mmc_stream, mmc_request, mmc, mmc_protocol, mmc_pool。

typedef struct mmc_buffer {
smart_str value;
unsigned int idx;
} mmc_buffer_t;

struct mmc_stream {
php_stream *stream;
int fd;
unsigned short port;
int chunk_size;
int status;
long failed;
long retry_interval;
mmc_buffer_t buffer;
mmc_stream_read read;
mmc_stream_readline readline;
struct {
char value[MMC_BUFFER_SIZE];
int idx;
} input;
};

struct mmc_request {
mmc_stream_t *io;
mmc_buffer_t sendbuf;
mmc_buffer_t readbuf;
char key[MMC_MAX_KEY_LEN + 1];
unsigned int key_len;
unsigned int protocol;
mmc_queue_t failed_servers;
unsigned int failed_index;
mmc_request_reader read;
mmc_request_parser parse;
mmc_request_value_handler value_handler;
void *value_handler_param;
mmc_request_response_handler response_handler;
void *failover_handler_param;
struct {
uint16_t reqid;
uint16_t seqid;
uint16_t total;
} udp;
};

struct mmc {
mmc_stream_t tcp;
mmc_stream_t udp;
mmc_request_t *sendreq;
mmc_request_t *readreq;
mmc_request_t *buildreq;
mmc_queue_t sendqueue;
mmc_queue_t readqueue;
char *host;
long timeout;
int persistent;
uint16_t reqid;
char *error;
int errnum;
};

struct mmc_pool {
mmc_t **servers;
int num_servers;
mmc_protocol_t *protocol;
mmc_hash_t *hash;
void *hash_state;
fd_set wfds;
fd_set rfds;
int in_select;
mmc_queue_t *sending;
mmc_queue_t *reading;
mmc_queue_t _sending1, _sending2;
mmc_queue_t _reading1, _reading2;
mmc_queue_t pending;
mmc_queue_t free_requests;
double min_compress_savings;
unsigned int compress_threshold;
mmc_failure_callback failure_callback;
void *failure_callback_param;
};
以及包含了很多函数指针的mmc_protocol结构体。
其中,mmc_pool包含一个二维数组的mmc(server),并用num_servers指明server的数量。mmc server中包含3个mmc_request数组,mmc_request应该是读写操作的单元。mmc_request中,使用mmc_stream作为io流,并包含了fd,给select函数监听。同时,mmc_request中还包含了read、send buffer,即mmc_buffer。这样,当需要读的时候,是从io中读,放到read buffer里;写的时候是从send buffer写到io中。从而完成与memcached服务器的互动。

ps:这里的连接可以是tcp也可以是udp。

2、序列化与压缩

memcache_pool.c中的mmc_compress和mmc_uncompress函数提供了压缩与解压的方法,它们都是static方法,被mmc_pack_value调用。该函数封装了序列化和压缩的功能。对于没有超长的数据,可以选择压不压缩,而过长的数据,一定被压缩,这是通过对flags的按位操作来实现的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: