什么是Redis:
- Redis是远程的
- Redis是基于内存的
- Redis是非关系型数据库
Redis的应用场景:
Redis安装:
Redis数据类型:
- String
可以是字符串、整数或浮点,统称为元素
//PHP中Redis操作
$redis = new \redis();
$result = $redis -> connect('127.0.0.1',6379);
//string类型
$redis -> delete('string1');
$redis -> set('string1','gdragon');
$val = $redis -> get('string1');
var_dump($val); //输出gdragon
$redis -> set("string1",4);
$redis -> incr("string1",4); //自增4
$val = $redis -> get("string1");
var_dump($val); // 输出 8
$redis = new \redis();
$result = $redis -> connect('127.0.0.1',6379);
//set类型
$redis -> delete("set1");
$redis -> sAdd("set1","A");
$redis -> sAdd("set1","B");
$redis -> sAdd("set1","C");
$redis -> sAdd("set1","C");
$val= $redis -> sCard("set1"); //set1元素个数
var_dump($val); //输出 3
$val = $redis -> sMembers("set1"); //以数组形式返回集合所有元素
var_dump($val);
$redis = new \redis();
$result = $redis -> connect('127.0.0.1',6379);
//list类型 (队列-先入先出)
$redis -> delete("list1");
$redis -> lPush("list1","A");
$redis -> lPush("list1","B");
$redis -> lPush("list1","C");
$redis -> lPush("list1","D");
$val = $redis -> rPop("list1");
var_dump($val); //输出 A
- Hash
有key-value的散列组,其中key是字符串,value是元素
//hash类型
$redis = new \redis();
$result = $redis -> connect('127.0.0.1',6379);
$redis -> delete("driver1");
$redis ->hSet("driver1","name","gdragon"); //设置司机姓名
$redis -> hSet("driver1","age",25); //设置司机年龄
$redis -> hSet("driver1","sex",1); //设置司机性别
$val = $redis -> hGet("driver1","name"); //获取司机姓名
var_dump($val); //输出 gdragon
$val = $redis -> hMget("driver1",array("name","age")); //同时获取司机姓名、年龄
var_dump($val);
//输出 array(2) { ["name"]=> string(7) "gdragon" ["age"]=> string(2) "25" }
- Sort Set
带分数的score-value有序集合,其中score为浮点,value为元素
//score set类型
$redis = new \redis();
$result = $redis -> connect('127.0.0.1',6379);
$redis -> delete("zset1");
$redis -> zAdd("zset1",100,"top");
$redis -> zAdd("zset1",90,"vi");
$redis -> zAdd("zset1",85,"gd");
$val = $redis -> zRange("zset1",0,-1); //从低到高
var_dump($val);
//输出 array(3) { [0]=> string(2) "gd" [1]=> string(2) "vi" [2]=> string(3) "top" }
$val = $redis -> zRevRange("zset1",0,-1); //从高到底
var_dump($val);
//输出 array(3) { [0]=> string(3) "top" [1]=> string(2) "vi" [2]=> string(2) "gd" }