-
Notifications
You must be signed in to change notification settings - Fork 7
/
redispool.c
89 lines (77 loc) · 2.48 KB
/
redispool.c
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include "redispool.h"
#include <stdlib.h>
static redisConnectionPool *redisConnectionPoolInit(
int size,
const char *hostname,
int port,
struct timeval timeout){
redisConnectionPool *c;
c = calloc(1, sizeof(redisConnectionPool));
if (c == NULL)
return NULL;
c->hostname = hostname;
c->port = port;
c->timeout = timeout;
c->connections = malloc(sizeof(redisContext*) * size);
if (c->connections == NULL)
return NULL;
c->allowedConnections = size;
c->usedConnections = 0;
return c;
}
redisConnectionPool *redisCreateConnectionPool(
int size,
const char *hostname,
int port,
struct timeval timeout){
return redisConnectionPoolInit(size, hostname, port, timeout);
}
void redisFreeConnectionPool(redisConnectionPool *pool){
if(pool != NULL && pool->connections != NULL){
if(pool->usedConnections > 0){
int i = 0;
for(; i<pool->usedConnections; i++){
if(pool->connections[i] != NULL){
redisFree(pool->connections[i]);
pool->connections[i] = NULL;
}
}
}
free(pool->connections);
pool->connections = NULL;
}
}
redisContext *redisGetConnectionFromConnectionPool(redisConnectionPool *pool){
if(pool != NULL && pool->connections != NULL ){
if(pool->usedConnections > 0){
redisContext *c;
pthread_mutex_lock(&pool->lock);
c = pool->connections[pool->usedConnections - 1];
pool->connections[pool->usedConnections - 1] = NULL;
pool->usedConnections--;
pthread_mutex_unlock(&pool->lock);
return c;
}
else{
return redisConnectWithTimeout(pool->hostname, pool->port, pool->timeout);
}
}
else {
return NULL;
}
}
void redisPutConnectionInConnectionPool(redisContext *c, redisConnectionPool *pool){
if(c != NULL && pool != NULL && !c->err && pool->connections != NULL
&& pool->usedConnections < pool->allowedConnections){
pthread_mutex_lock(&pool->lock);
pool->connections[pool->usedConnections] = c;
pool->usedConnections++;
pthread_mutex_unlock(&pool->lock);
}
}
int redisConnectionsInConnectionPool(redisConnectionPool *pool){
return pool->usedConnections;
}
int redisConnectionPoolDepth(redisConnectionPool *pool){
return pool->allowedConnections;
}