Redis与网站架构 @joyqi

来源:互联网 发布:linux基础入门ppt 编辑:程序博客网 时间:2024/05/18 02:11
什么是Redis?
? REmote DIctionary Server 缩写
? 一个基于内存的网络存储系统
? 丰富的数据结构(sets, sorted sets,hashes, list ...)
? 本质是key-value,但是与memcached不同的是,value的类型得到了扩展

用Hashes保存字段
$user = array(
'id' => 123,
'name' => 'joyqi',
'mail' => 'magike.net@gmail.com',
'created' => 1212312312
);
$redis->hMSet(‘user:123’, $user);
print_r($redis->hGetAll(‘user:123’));
[root@localhost redis]# php db1.php     
Array
(
    [id] => 123
    [name] => goith
    [age] => 12
)

用Sets保存关系

<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);


$questionid = 123;
$tagids = array(11,22,33);
foreach( $tagids as $sort=>$tagid){

$redis->zAdd('question_tag:'.$questionid,$sort,$tagid);
}
$val = $redis->zRange('question_tag:123',0,-1);
print_r($val);
print_r("\n");

[root@localhost redis]# php db2.php
Array
(
[0] => 11
[1] => 22
[2] => 33
)


有了Redis,支持实时搜
索的门槛被大大降低

分词加Redis集合实现索引

$questionTitle = ‘搜索技术’;
$questionId = 123;
$words = fenci($questionTitle); // array(‘搜索’, ‘技术’);
foreach ($words as $word) {
$redis->zAdd(‘w:’ . md5($word), 1, $questionId);
}
// 索引完成

Redis集合Union操作实现查询

$keywords = ‘怎样实现搜索技术’;
$words = fenci($keywords); // array(‘怎样’, ‘实现’, ‘搜索’, ‘技术’);
$indexes = array_map(function ($word) {
return ‘w:’ . md5($word);
}, $words);
$redis->zUnion(‘result’, $indexes, array_fill(0, count($indexes), 1),
‘sum’);
print_r($redis->zRevRange(‘result’, 0, -1));


原创粉丝点击