Gearmand是一个用来把工作委派给其它机器、分布式的调用更适合做某项工作的机器、并发的做某项工作在多个调用间做负载均衡、或用来调用其它语言的函数的系统。
简单来讲,就是客户端程序把请求提交给gearmand,gearmand会把请求转发给合适的worker来处理这个请求,最后还通过gearmand返回结果。
运行流程:
Client --> Job --> Worker
在server1中启动gearmand:
systemctl start gearmand
systemctl status gearmand
在server3中:
yum install unzip -y
unzip lib_mysqludf_json-master.zip
安装 mariadb-devel:
yum install -y mariadb-devel.x86_64
编译模块:
yum install gcc -y
cd lib_mysqludf_json-master
gcc $(mysql_config --cflags) -shared -fPIC -o lib_mysqludf_json.so lib_mysqludf_json.c
将模块放到mysql插件目录:
cp lib_mysqludf_json-master/lib_mysqludf_json.so /usr/lib64/mysql/plugin/
在数据库中查看:
MariaDB [(none)]> show global variables like 'plugin_dir';
注册udf函数:
MariaDB [(none)]> CREATE FUNCTION json_object RETURNS STRING SONAME 'lib_mysqludf_json.so';
安装插件管理gearman的分布式队列:
tar zxf gearman-mysql-udf-0.6.tar.gz
yum install libevent-devel-2.0.21-4.el7.x86_64.rpm libgearman-* -y
cd gearman-mysql-udf-0.6
./configure --libdir=/usr/lib64/mysql/plugin/ --with-mysql
make && make install
注册udf函数:
MariaDB [(none)]> CREATE FUNCTION gman_do_background RETURNS STRING SONAME 'libgearman_mysql_udf.so';
MariaDB [(none)]> CREATE FUNCTION gman_servers_set RETURNS STRING SONAME 'libgearman_mysql_udf.so';
查看函数:
MariaDB [(none)]> select * from mysql.func;
指定gman服务信息:
MariaDB [(none)]> SELECT gman_servers_set('172.25.254.1:4730');
编写mysql触发器:
vim test.sql
use test;
#CREATE TABLE `test` (`id` int(7) NOT NULL AUTO_INCREMENT, `name` char(8) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#INSERT INTO `test` VALUES (1,'test1'),(2,'test2'),(3,'test3'),(4,'test4'),(5,'test5'),(6,'test6'),(7,'test7'),(8,'test8'),(9,'test9');
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 -p123 < test.sql
查看触发器:
MariaDB [(none)]> SHOW TRIGGERS FROM test;
在server1中:
编写gman的worker端:
cd /usr/local
vim worker.php
<?php
$worker = new GearmanWorker();
$worker->addServer();
$worker->addFunction('syncToRedis', 'syncToRedis');
$redis = new Redis();
$redis->connect('172.25.254.2', 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);
}
?>
后台运行worker:
nohup php /usr/local/worker.php &> /dev/null &
修改数据库内容:
MariaDB [test]> update test set name='westos' where id=2;
在redis上查看:
redis-cli
127.0.0.1:6379> get 2
"westos"
在页面查看,数据同步: