1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
| #include "config.h"
#include <stdio.h>
#include <event.h>
#include <evhttp.h>
#include <unistd.h>
#include <libmemcached/memcached.h>
#include <mysql/mysql.h>
static memcached_st *mc = NULL;
static MYSQL *mysql = NULL;
static MYSQL_RES *res = NULL;
static MYSQL_ROW row;
static char buf[MAXLEN];
void init_memcache() {
mc = memcached_create(NULL);
memcached_server_add(mc, MEMCACHE_HOST, MEMCACHE_PORT);
}
void init_mysql() {
if ((mysql = mysql_init(NULL)) == NULL) {
fprintf(stderr, "mysql_init\n");
exit(-1);
}
if (mysql_real_connect(
mysql,
MYSQL_HOST,
MYSQL_USER,
MYSQL_PASS,
MYSQL_DATABASE,
MYSQL_PORT,
MYSQL_SOCK,
MYSQL_FLAGS
) == NULL) {
fprintf(stderr, "mysql_connect[%d]: %s\n", mysql_errno(mysql), mysql_error(mysql));
exit(-1);
}
}
void set_handler(struct evhttp_request *req, void *arg) {
char *uri = req->uri;
if (strnlen(uri, MAXLEN) == MAXLEN || *uri == '\0') {
evhttp_connection_free(req->evcon);
return;
}
uri++;
sprintf(buf, "SELECT url FROM url WHERE url = '%s' limit 1", uri);
mysql_query(mysql, buf);
res = mysql_store_result(mysql);
if (mysql_num_rows(res)) {
fprintf(stderr, "num_rows: %d\n", mysql_num_rows(res));
memcached_set(mc, uri, strlen(uri), "1", 1, 0, 0); evhttp_send_reply(req, HTTP_OK, "OK", NULL); }
else {
evhttp_send_reply(req, HTTP_NOTFOUND, "NOT FOUND", NULL);
}
}
int main(int argc, char **argv) {
init_memcache();
init_mysql();
event_init();
struct evhttp *httpd = evhttp_start(SET_HOST, SET_PORT);
evhttp_set_gencb(httpd, set_handler, NULL);
event_dispatch();
evhttp_free(httpd);
return 0;
} |