Created
April 4, 2018 01:27
-
-
Save corvofeng/4b720cc40969af771c350ce104df9b30 to your computer and use it in GitHub Desktop.
redis双线程. 一个线程用来PUSH, 另一个线程为SUBSCRIBE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
*======================================================================= | |
* Filename:redis_thread.c | |
* | |
* Version: 1.0 | |
* Created on: April 03, 2018 | |
* | |
* Author: corvo | |
*======================================================================= | |
*/ | |
// gcc redis_thread.c -lhiredis -lpthread -I/usr/include/hiredis -g | |
// ./a.out | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <hiredis.h> | |
void* run_push(void* context) { | |
redisContext *c = (redisContext*) context; | |
redisReply *reply; | |
// first auth | |
reply = (redisReply*) redisCommand(c, "AUTH %s", "1234"); | |
printf("AUTH: %s\n", reply->str); | |
freeReplyObject(reply); | |
while(1) { | |
reply = (redisReply*)redisCommand(c, | |
"LPUSH %s %s", "test_que", "12345"); | |
if(reply->type == REDIS_REPLY_INTEGER) { | |
printf("%d\n", reply->integer); | |
} else { | |
printf("Error\n"); | |
} | |
freeReplyObject(reply); | |
printf("helloworld\n"); | |
sleep(1); | |
} | |
} | |
void *run_sub(void* context) { | |
redisContext *c = (redisContext*) context; | |
redisReply *reply; | |
// first auth | |
reply = (redisReply*) redisCommand(c, "AUTH %s", "1234"); | |
printf("AUTH: %s\n", reply->str); | |
freeReplyObject(reply); | |
reply = (redisReply*) redisCommand(c,"SUBSCRIBE ever_chanel"); | |
freeReplyObject(reply); | |
while(redisGetReply(c, (void*)&reply) == REDIS_OK) { | |
// consume message | |
if (reply == NULL) continue; | |
if ( reply->type == REDIS_REPLY_ARRAY && reply->elements == 3 ) { | |
if ( strcmp( reply->element[0]->str, "subscribe" ) != 0 ) { | |
printf( "Received[%s] channel %s: %s\n", | |
reply->element[0]->str, | |
reply->element[1]->str, | |
reply->element[2]->str ); | |
} | |
} | |
freeReplyObject(reply); | |
} | |
} | |
int main (int argc, char **argv) { | |
redisContext *c_push = redisConnect("127.0.0.1", 6379); | |
redisContext *c_sub = redisConnect("127.0.0.1", 6379); | |
pthread_t t_push; | |
pthread_t t_sub; | |
pthread_create(&t_push, NULL, run_push, c_push); | |
pthread_create(&t_sub, NULL, run_sub, c_sub); | |
pthread_join(t_push, NULL); | |
pthread_join(t_sub, NULL); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment