redis分布式集群redis和mysql数据的同步

1、原理框架图

在这里插入图片描述

 2、该操作以这个为基础:https://mp.csdn.net/postedit/99671504

server7:

需要的安装包:
    libgearman-1.1.12-18.el7.x86_64.rpm
    libgearman-devel-1.1.12-18.el7.x86_64.rpm
    libevent-devel-2.0.21-4.el7.x86_64.rpm
yum install  *    安装上边的所有包
    lib_mysqludf_json-master.zip
    gearman-mysql-udf-0.6.tar.gz 
生成json函数,将数据转换成json格式,这样方便reids识别
    unzip lib_mysqludf_json-master.zip
    cd lib_mysqllib_mysqludf_json.c  
        lib_mysqludf_json.html  lib_mysqludf_json.sql  README.mdudf_json-master
        
    yum install gcc  
    yum install mysql-devel
    #生成lib_mysqludf_json.so模块
    gcc $(mysql_config --cflags) -shared -fPIC -o lib_mysqludf_json.so lib_mysqludf_json.c 
    cp lib_mysqludf_json.so /usr/lib64/mysql/plugin/
    
    进入数据库:
    mysql:
        show global variables like 'plugin_dir';    查看插件目录
        #创建mysql的函数:
        CREATE FUNCTION json_object RETURNS STRING SONAME 'lib_mysqludf_json.so';
        查看创建的函数
        select * from mysql.func;
创建mysql_udf模块:
    tar zxf gearman-mysql-udf-0.6.tar.gz
    cd gearman-mysql-udf-0.6
    ./configure --libdir=/usr/lib64/mysql/plugin/
    make && make install

    mysql: 
        create function gman_servers_set returns string soname 'libgearman_mysql_udf.so';
        CREATE FUNCTION gman_do_background RETURNS STRING SONAME 'libgearman_mysql_udf.so';
    select * from mysql.func;    查看函数

    SELECT gman_servers_set('172.25.17.105:4730');
vim test.sql:
DELIMITER $$
CREATE TRIGGER datatoredis AFTER UPDATE ON test FOR EACH ROW BEGIN
    SET @RECV=gman_do_background('syncToRedis', json_object(NEW.id as `id`, NEW.name as `name`)); 
  END$$
DELIMITER ;

mysql < test.sql

server5:

tar zxf gearman-1.1.2.tgz
cd gearman-1.1.2
    phpize
    ./configure 
    make && make install
    cd /usr/lib64/php/modules/
    cd /etc/php.d/
    cp redis.ini gearman.ini
    vim gearman.ini 
        extension=gearman.so
    /etc/init.d/php-fpm reload
    php -m |grep gearman    查看gearman模块

    cd /usr/local/
    vim worker.php   
        addServer();
        $worker->addFunction('syncToRedis', 'syncToRedis');

        $redis = new Redis();
        $redis->connect('172.25.17.106', 6379);

        while($worker->work());
        function syncToRedis($job)
        {
                global $redis;
                $workString = $job->workload();
                $work = json_decode($workString);
                if(!isset($work->id)){
                        return false;
                }
        $redis->set($work->id, $work->name);
       }
    ?>
nohup php /usr/local/worker.php &      打入后台运行

测试:

server7:
    mysql:
    mysql> update test set name='haha';
        Query OK, 9 rows affected (0.09 sec)
        Rows matched: 9  Changed: 9  Warnings: 0
server6:
    redis-cli
    get 1        查看数据同步情况

浏览器:http://172.25.17.105/test.php

 

 

 

 

 

 

你可能感兴趣的:(web)