技术开发 频道

张宴:Tokyo Cabinet数据库及其扩展应用

  借助MySQL触发器,以及为MySQL 5.1 编写的扩展插件函数,来让TCSQL当MySQL的从库:

  json_object()、 urlencode()、http_post()

  接下来是一个示例:通过MySQL命令行连接到MySQL服务器,执行以下SQL,对sns_feed表创建三个MySQL触发器:sns_feed_insert、sns_feed_update、sns_feed_delete,当MySQL的sns_feed表发生增、删、改操作时,自动将修改的记录内容通过HTTP POST到TCSQL数据库(192.168.8.34:3888)。

  TCSQL“从库”Insert触发器

  DELIMITER |

  DROP TRIGGER
IF EXISTS sns_feed_insert;

  CREATE TRIGGER sns_feed_insert

  AFTER INSERT
ON sns_feed

  
FOR EACH ROW BEGIN

  
SET @tcsql_result_json = (SELECT json_object(feedid as pkey,appid,icon,uid,username,dateline,friend,hash_template,hash_data,title_template,title_data,body_template,body_data,body_general,image_1,image_1_link,image_2,image_2_link,image_3,image_3_link,image_4,image_4_link,target_ids,id,idtype,hot) FROM sns_feed WHERE feedid = NEW.feedid limit 1);

  
SET @tcsql_result_eval = (SELECT http_post('192.168.8.34', '3888', 'command=insert', urlencode(@tcsql_result_json)));

  
END |

  DELIMITER ;

  TCSQL“从库”update触发器

  DELIMITER |

  DROP TRIGGER
IF EXISTS sns_feed_update;

  CREATE TRIGGER sns_feed_update

  AFTER UPDATE
ON sns_feed

  
FOR EACH ROW BEGIN

  
SET @tcsql_result_json = (SELECT json_object(feedid as pkey,appid,icon,uid,username,dateline,friend,hash_template,hash_data,title_template,title_data,body_template,body_data,body_general,image_1,image_1_link,image_2,image_2_link,image_3,image_3_link,image_4,image_4_link,target_ids,id,idtype,hot) FROM sns_feed WHERE feedid = OLD.feedid limit 1);

  
SET @tcsql_result_eval = (SELECT http_post('192.168.8.34', '3888', 'command=insert', urlencode(@tcsql_result_json)));

  
END |

  DELIMITER ;

  TCSQL“从库”delete触发器

  DELIMITER |

  DROP TRIGGER
IF EXISTS sns_feed_delete;

  CREATE TRIGGER sns_feed_delete

  AFTER DELETE
ON sns_feed

  
FOR EACH ROW BEGIN

  
SET @tcsql_result_eval = (SELECT http_post('192.168.8.34', '3888', concat('command=delete&where=pkey:NUMEQ:', OLD.feedid), ''));

  
END |

  DELIMITER ;

  TCSQL的数据update更新优化

  TCTDB+Tokyo Tyrant时,如果只更新一条记录中的某个字段的值,PHP客户端需要先读回Tokyo Tyrant中该记录的全部字段内容到一个PHP数组,再修改此数组中该字段的值,最后再将该数组写回Tokyo Tyrant ,来回通过网络传输记录全部字段内容,速度慢、效率低。

  TCSQL可以对部分字段内容进行更新,在TCSQL内部处理完成修改操作,没有不必要的TCP传输。

0
相关文章