第一步:下载Hiredis并且编译,过程略,百度一大堆
第二步:查看mysql的UDF编写方法(其实就导入mysql.h头文件,然后根据规则创建接口函数就行了)
第三步:写代码。不喜欢多BB直接贴代码
redis.h 文件
#ifndef _REDIS_H_
#define _REDIS_H_
#include <iostream>
#include <string.h>
#include <string>
#include <stdio.h>
#include <sys/time.h>
#include <hiredis/hiredis.h>
class Redis
{
public:
struct timeval tv;
volatile bool isLock;
Redis(){
this->isLock=false;
}
~Redis()
{
redisFree(this->_connect);
this->_reply = NULL;
}
bool connect(std::string host, int port)
{
this->_connect = redisConnect(host.c_str(), port);
if(this->_connect != NULL && this->_connect->err)
{
printf("connect error: %s\n", this->_connect->errstr);
return 0;
}
return 1;
}
std::string get(std::string key)
{
this->_reply = (redisReply*)redisCommand(this->_connect, "GET %s", key.c_str());
std::string str = this->_reply->str;
freeReplyObject(this->_reply);
return str;
}
void set(std::string key, std::string value)
{
redisCommand(this->_connect, "SET %s %s", key.c_str(), value.c_str());
}
void exec(std::string cmd){
redisCommand(this->_connect,cmd.c_str());
}
private:
redisContext* _connect;
redisReply* _reply;
};
#endif //_REDIS_H_
redis.cpp文件
#include "redis.h"
#include "/opt/mysql-5.7.17/include/mysql.h"
#include <vector>
#include <climits>
#include <unistd.h>>
#include <sstream>
#include "get_config.h"
static Redis *r=NULL;
static int CONNECTPOOL=5;
static int MAXCONNECTPOOL=20;
static int LOCKINTERVAL=1;
static string HOST="192.168.2.120";
static int PORT=6379;
static int EXPIRETIME=100;
static long operatorCount=0;
static std::vector<Redis *> *redisPool=NULL;
static map<string,string> configMap;
extern "C" {
void init_config(){
if(ReadConfig("redis_config",configMap)){
map<string,string>::iterator it;
stringstream ss;
it=configMap.find("CONNECTPOOL");
if(it!=configMap.end()){
ss<<(it->second);
ss>>CONNECTPOOL;
}
//-----------------