mysql-udf的使用---mysql自动同步数据到redis.redis连接池的实现

本文介绍了如何使用MySQL的用户定义函数(UDF)将数据自动同步到Redis,并实现了Redis连接池。首先,通过编译Hiredis来创建redis.so,然后在MySQL中创建UDF函数,包括执行Redis命令和释放连接的功能。通过配置文件和ldconfig管理库路径,确保MySQL能够找到并使用这些函数。最后,展示了如何在SQL查询中调用这些函数,以及连接池的工作原理。
摘要由CSDN通过智能技术生成

第一步:下载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;
	}
//-----------------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值