用mysql触发器自动更新memcache

mysql 5.1支持触发器以及自定义函数接口(UDF)的特性,如果配合libmemcache以及Memcached Functions for MySQL,就能够实现memcache的自动更新。简单记录一下安装测试步骤。

安装步骤

  • 安装memcached,这个步骤很简单,随处可见
  • 安装mysql server 5.1RC,安装办法也很大众,不废话了
  • 编译libmemcached,解压后安装即可
    ./configure; make; make install
  • 编译Memcached Functions for MySQL,在http://download.tangent.org/找一个最新的版本下载就是,
    ./configure --with-mysql=/usr/local/mysql/bin/mysql_config --libdir=/usr/local/mysql/lib/mysql/
    make
    make install
  • 接下来有两个办法让Memcached Functions for MySQL在mysql中生效
    • 在mysql的shell中执行memcached_functions_mysql源码目录下的sql/install_functions.sql,这会把memcache function作为UDF加入mysql
    • 运行memcached_functions_mysql源码目录下的utils/install.pl,这是一个perl脚本,作用同上一条

测试memcache function

以下测试脚本摘自memcached_functions_mysql的源码目录,有兴趣可以试试

drop table if exists urls;
create table urls (
  id int(3) not null,
  url varchar(64) not null default '',
  primary key (id)
  );

select memc_servers_set('localhost:11211');
select memc_set('urls:sequence', 0);

DELIMITER |

DROP TRIGGER IF EXISTS url_mem_insert;
CREATE TRIGGER url_mem_insert
BEFORE INSERT ON urls
FOR EACH ROW BEGIN
    SET NEW.id= memc_increment('urls:sequence');
    SET @mm= memc_set(concat('urls:',NEW.id), NEW.url);
END |

DELIMITER ;

insert into urls (url) values ('http://google.com');
insert into urls (url) values ('http://www.ooso.net/index.php');
insert into urls (url) values ('http://www.ooso.net/');
insert into urls (url) values ('http://slashdot.org');
insert into urls (url) values ('http://mysql.com');
select * from urls;

select memc_get('urls:1');
select memc_get('urls:2');
select memc_get('urls:3');
select memc_get('urls:4');
select memc_get('urls:5');

8 replies on “用mysql触发器自动更新memcache”

  1. 请问我在安装的时候出现这个错误

    Error Code : 1126
    Can’t open shared library ‘libmemcached_functions_mysql.so’ (errno: 22 libmemcached_functions_mysql.so: cannot open shared object file: No such file or directory)
    (0 ms taken)

    Error Code : 1126
    Can’t open shared library ‘libmemcached_functions_mysql.so’ (errno: 22 libmemcached_functions_mysql.so: cannot open shared object file: No such file or directory)
    (0 ms taken)

    如何解决呢~
    在此先谢过大哥

  2. 问题解决了 原先用的是ubuntu系统默认的mysql5.0的
    后来仔细看了下您的文章,自己编译装上了 mysql5.1的 问题解决了~
    嘿嘿~

    谢谢 Volcano

  3. 看你们都用的是mysql5.1 版本,不知道我用的mysql5.5 版本的会不会有冲突,在执行第5步添加memcache UDF 函数的时候总是有问题,报错如下:
    ERROR 1126 (HY000) at line 1: Can’t open shared library ‘libmemcached_functions_mysql.so’ (errno: 22 libmemcached_functions_mysql.so: cannot open shared object file: No such file or directory)
    我在mysql的配置文件中添加了指定的plugin_dir 目录后又报错如下:
    ERROR 1126 (HY000) at line 1: Can’t open shared library ‘libmemcached_functions_mysql.so’ (errno: 0 /usr/local/mysql/lib/mysql/plugin/libmemcached_functions_mysql.so: cannot open shared object file: Permission denied)

Comments are closed.