Today,Mayuyu to learn how to operate a Redis database in C + +. Implemented through the Hiredis.h interface , currently available only in Linux environments.
The hiredis.h is:Https://github.com/redis/hiredis
The following four methods are mainly included
1. rediscontext* redisconnect (const char *IP, int port)
This function is used to connect to the Redis database, two parameters are the IP and port of the Redis database, the port number is generally 6379. Similar
also provides a function for the connection time-out limit, which is
rediscontext* redisconnectwithtimeout (const char *IP, int port, Timeval TV).
2. void *rediscommand (Rediscontext *c, const char *format ...)
This function is used to execute commands in the Redis database, the first parameter is the Rediscontext returned by the connected database, and the remaining parameters
As a prinf () function in the C language.
The return value of this function is void*, but is generally cast to the redisreply type for further processing.
3. void Freereplyobject (void *reply)
Releases the memory occupied by the Redisreply returned after Rediscommand execution.
4. void Redisfree (Rediscontext *c)
Releases the connection generated by the Redisconnect ().
Next is to let Mayuyu to teach you how to install Hiredis it!
First download the hiredis.tar.gz package on the website, extract found inside there is a Makefile file, and then perform make to compile, get
Then put the libhiredis.so into the /usr/local/lib/ and put the hiredis.h in the /usr/local/inlcude/hiredis/ the.
Or use the command make install configuration directly. Such as
The next step is to use it directly in the program. Include #include in your program.
In order to operate conveniently, generally we need to write a header file class, the method of this class according to their own project needs to be added appropriately. As follows
Code: REDIS.H
#ifndef _redis_h_#define _redis_h_#include <iostream> #include <string.h> #include <string> #include <stdio.h> #include Redis.cpp
#include "redis.h" int main () {Redis *r = new Redis (), if (!r->connect ("192.168.13.128", 6379)) {printf ("Connect error!\ n "); return 0;} R->set ("name", "Mayuyu");p rintf ("Get The name is%s\n", R->get ("name"). C_STR ());d elete R;return 0;}
Makefile file
Redis:redis.cpp redis.hg++ redis.cpp-o redis-l/usr/local/lib/-lhiredisclean:rm redis.o Redis
Note that before g++ and RM are all a TAB key.
You need to add parameters at compile time, assuming the file is redis.cpp, then compile the command as follows
g++ Redis.cpp-o redis-l/usr/local/lib/-lhiredis
If the dynamic library fails to load at the time of execution, the following configuration is required
Create a new file usr-libs.confin the /etc/ld.so.conf.d/ directory with the following content: /usr/local/lib
As shown
Then use the command /sbin/ldconfig to update the configuration.
C + + operations Redis database