C Basic Redis Cache access

Source: Internet
Author: User
Tags server memory redis server

Introduction

First of all, the Redis installation, the environment used here is.

4.4. 0--generic ([email protected]5.3.  1201604135.3. 1-14ubuntu2) #: £ º  .

Redis is very easy to install for Ubuntu. Here to install the source code. The installation code is as follows

wget http://download.redis.io/releases/redis-3.0.6.tar.gztar xzf redis-3.0. 6 . TAR.GZCD Redis-3.0. 6  Make

After the installation my environment is

Let's test it. Installation results. Start the Redis-server server first.

Start the REDIS-CLI client again

Let's start testing.

Everything is fine after the test. The installation on Redis Linux is basically complete. A more detailed reference

Redis Official Website Tutorial very detailed http://www.redis.net.cn/tutorial/3501.html

Objective

Now we install the driver for Redis C access. Hiredis. It starts with a download installation. I downloaded the installation directly from the Hiredis git website.

Hiredis Source Https://github.com/redis/hiredis

wget Https://github.com/redis/hiredis/archive/master.zipunzip Master.zip

The installation will see this environment

Execute the Install command

Makesudo make Install

Essence for make install perform the following steps

Mkdir-p/usr/local/include/hiredis/usr/local/-a hiredis.h async.h read.h sds.h adapters/usr/local/include/< c1>-a libhiredis.so/usr/local/lib/libhiredis.so. 0.13  /usr/local/lib && ln-sf libhiredis.so. 0.13  -alibhiredis.a/usr/local/-p/usr/local/lib/-a Hiredis.pc/usr/local/lib/pkgconfig

Now basically the Hiredis driver has been installed. Explained later, the driver provides the API.

The common APIs are as follows.

/** Redis link function returns the Redis context. * IP: IP of the link address * port: Link Port *: Returns REDIS context, NULL means get failed*/Rediscontext*redisconnect (Const Char*ip,intPort)/** Perform redis operations Command, return the resulting set of results * Context:redisconnect returned Redis context object * Format: equivalent to printf format control * ... : The following variable parameter, which corresponds to the format character in format *: Returns the resulting set of results*/void*rediscommand (Rediscontext *context,Const Char*format, ...);/** Release Redis command operation returned result set * Reply:rediscommand returned result set*/voidFreereplyobject (void*reply);/** Release Link context * Context:redisconnect returned link context*/voidRedisfree (Rediscontext *context);

More detailed explanation we can look at the source interface file Hiredis/hiredis.h. For example

The first one is the REDISCONTEXT context structure returned by Redisconnect/*Context for a connection to Redis*/typedefstructRediscontext {intErr/*error flags, 0 when there is no Error*/    Charerrstr[ -];/*String representation of error when applicable*/    intFD; intflags; Char*obuf;/*Write Buffer*/Redisreader*reader;/*Protocol Reader*/    enumRedisconnectiontype Connection_type; structTimeval *timeout; struct {        Char*host; Char*source_addr; intPort;    } TCP; struct {        Char*path; } Unix_sock;} Rediscontext; There is also a command set returned by Rediscommand/*The reply object returned by Rediscommand ()*/typedefstructredisreply {intType/*redis_reply_**/    Long LongInteger/*The integer when type is Redis_reply_integer*/    intLen/*Length of String*/    Char*STR;/*used for both Redis_reply_error and redis_reply_string*/size_t elements;/*Number of elements, for Redis_reply_array*/    structRedisreply **element;/*elements vector for Redis_reply_array*/} redisreply;

About the Hiredis basic C-drive interface, the explanation is complete. Start writing the demo test later. The best way to understand it is to look at the official source code and the test codes.

Body

Let's start with a simple demo test. Simpleget.c

#include <stdio.h>#include<stdlib.h>#include/** Request Redis Network cache server memory.*/intMainintargcChar*argv[]) {Rediscontext*conn = Redisconnect ("127.0.0.1",6379); if(NULL = =conn) {fprintf (stderr,"redisconnect 127.0.0.1:6379 error!\n");    Exit (Exit_failure); }       if(conn->err) {fprintf (stderr,"Redisconect error:%d\n", conn->err);        Redisfree (conn);    Exit (Exit_failure); }           //here Redisconnect linked objects are createdRedisreply *reply = Rediscommand (conn,"get foo"); if(reply && Reply->type = =redis_reply_string) {printf ("get foo =%s\n", reply->str); } printf ("Reply->type =%d\n", reply->type); //release This objectFreereplyobject (Reply); //releasing the Hiredis context objectRedisfree (conn); return 0;}

The Compile command is

Gcc-wall-ggdb-o Simpleget.  out Simpleget.c-lhiredis

The final test result is


This shows that the flow is running through. To expand here, sometimes it's troublesome to look up a function or macro definition on Linux. The way I used to be

' redis_reply_string '

The stupid method is also very practical. The result of the lookup is the excerpt from the above redis_reply_string definition in the hiredis/read.h section below

#define Redis_reply_string 1#define redis_reply_array 2#define redis_reply_integer 3#define REDIS _reply_nil 4#define redis_reply_status 5#define Redis_reply_error 6

The values returned are distinguished by these macro enumerations. Actually here is basically a basic introduction to using Redis interfaces. Let's go back to the operation code for Operation List SETLIST.C

#include <stdio.h>#include<stdlib.h>#include<signal.h>#include/** Request Redis Network cache server memory.*/intMainintargcChar*argv[]) {    //ignore the server exit, causing the current process to exitsignal (sigpipe, sig_ign); Rediscontext*conn = Redisconnect ("127.0.0.1",6379); if(NULL = =conn) {fprintf (stderr,"redisconnect 127.0.0.1:6379 error!\n");    Exit (Exit_failure); }       if(conn->err) {fprintf (stderr,"Redisconect error:%d\n", conn->err);        Redisfree (conn);    Exit (Exit_failure); }           //here Redisconnect linked objects are createdFreereplyobject (Rediscommand (conn,"Lpush mylist foo")); Freereplyobject (Rediscommand (conn,"Lpush mylist Bar")); Redisreply*reply = Rediscommand (conn,"Lrange mylist 0-1"); if(reply && Reply->type = = Redis_reply_array && Reply->elements = =2) {printf ("%s%s\n", reply->element[0]-&GT;STR, reply->element[1]->str); }       Else{printf ("Rediscommand [Lrange mylist 0-1] error:%d.%s\n", Reply->type, reply->str); }       //release This objectFreereplyobject (Reply); //releasing the Hiredis context objectRedisfree (conn); return 0;}

Compiling code

Gcc-wall-ggdb-o setlist.  out Setlist.c-lhiredis

The operation results are as follows

For more details, please refer to the source code on Hiredis git.

Postscript

To here about C simple Use control Redis server, basically finished. Mistakes are inevitable. Please correct me.

/**********************************************************************

* * Understand directly to the masters rather than to their students.

**--Abel

***********************************************************************/

C Basic Redis Cache access

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.