鱼喃

听!布鲁布鲁,大鱼又在那叨叨了

redis入门(4)---在PHP中使用redis

在php中有两种方式操作redis数据库

  • predis (使用php代码实现) (下载源代码)
  • phpredis (php扩展)

本文以predis为例

添加autoload(以predis为例)

1
require_once('../dsa.php'); 

连接

1
2
3
4
5
6
7
8
$redis = new Predis\Client();
//默认连接 127.0.0.1:6379
//可以自己指定
$redis = new Predis\Client(array(
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379
));

操作示例

字符串类型

1
2
3
4
5
6
7
8
9
10
var_dump($client->set('str', 'val'));
var_dump($client->get('str'));
var_dump($client->mset(array(
'str1' => 'v1',
'str2' => 'v2',
'str3' => 'v3'
)));
//与下面这条效果一致
var_dump($client->mset('str1', 'v1', 'str2', 'v2'));
var_dump($client->mget(array('str1', 'str2', 's3')));

散列类型

1
2
3
4
5
6
7
8
$user = array(
'uid' => 2,
'name' => 'newnius'
);
var_dump($client->hmset('user:1', $user));
var_dump($client->hmget('user:1', array_keys($user)));
var_dump($client->hgetall('user:1'));
//hgetall 返回关联数组

列表类型

1
2
3
4
$list = array('1', '2', '3');
var_dump($client->lpush('l1', '2', '1', '3'));
var_dump($client->lpush('l1', $list));
var_dump($client->lrange('l1', '0', '-1'));

集合类型

1
2
3
4
$set = array('2', '1', '3', '2');
var_dump($client->sadd('set1', $set));
var_dump($client->sadd('set1', '2', '1', '3'));
var_dump($client->smembers('set1'));

有序集合

1
2
3
4
5
6
7
8
$set = array(
'2' => '100',
'1' => '90',
'3' => '95'
);
var_dump($client->zadd('z1', $set));
var_dump($client->zadd('z1', '100', '2', '90', '1', '95', '3'));
var_dump($client->zrange('z1', '0', '-1'));
sort
1
2
3
4
5
6
7
8
9
var_dump($client->sort('post_id_list', array(
'by' => 'post:*->time',
'limit' => array(0,5),
'get' => array('post:*->title', '#'),
'sort' => 'asc',
'alpha' => true,
'store' => 'result'
)));
var_dump($client->lrange('result', '0', '-1'));