C language access redis database through Hiredis

C language to access redis database

  1. Prepare Hiredis library
    Centos7 or 8
    hiredis-0.11.0.tar.gz
    yum install redis
  2. Install the Hiredis library
    Unzip the Hiredis compressed package
    tar -zcvf hiredis-0.11.0.tar.gz
    ./Execute
    make && make install in the Hiredis root directory
  3. Edit the dynamic library link
    Create a directory and copy the files to the directory
    mkdir /usr/lib/hiredis
    cp libhiredis.so /usr/lib/hiredis #Dynamic link library libhiredis.so to /usr/lib/hiredis
    mkdir /usr/include/ hiredis
    cp hiredis.h /usr/include/hiredis
    Method 1:
    Add the path /usr/local/lib directly to the file /etc/ld.so.conf. Add directly at the end of the file /etc/ld.so.conf: /usr/local/lib
    Method 2:
    echo'/usr/local/lib' >>/etc/ld.so.conf
    ldconfig
    execute sudo /sbin/ldconfig Next, update the system dynamic library configuration
  4. Write the test source code
    test.c and makefile in the same directory, execute make, the test executable file will be generated in the directory
  5. Run the test
    ./test
    console to print 1234
    Redis-cli to view the
    makefile file with the foo key value
LIBDIR= -L/usr/local/lib  
LIBSO = -lhiredis  
CFLAG = -Wall -g  
  
all:test

test:test.o
	gcc ${CFLAG} -o $@ $< ${LIBDIR} ${LIBSO}  
%.o%.c:
	gcc -c -o $@ $^  
  
clear:
	rm -f *.o

test.c file source code

#include <stdio.h>  
#include <hiredis/hiredis.h>  
  
int main()  
{
    
      
    redisContext* conn = redisConnect("127.0.0.1",6379);  
    if(conn->err)   printf("connection error:%s\n",conn->errstr);  
  
    redisReply* reply = redisCommand(conn,"set foo 1234");  
    freeReplyObject(reply);  
  
    reply = redisCommand(conn,"get foo");  
  
    printf("%s\n",reply->str);  
    freeReplyObject(reply);  
  
    redisFree(conn);  
  
    return 0;  
  
}

Note: Dynamic library citation is the key, detailed source code can be obtained by contacting the blogger

Guess you like

Origin blog.csdn.net/weloveut/article/details/108887535