php操作redis

php操作redis


redis技术文档https://github.com/phpredis/phpredis

connect.php

//实例化redis类
$redis=new \Redis();
//链接redis
$redis->connect("127.0.0.1",7200);


string类型操作


案例:string.php

<?php

$redis=new \Redis();

$redis->connect('127.0.0.1',7200);

//string操作
$redis->delete("string1");

$redis->set("string1","val1");
$val=$redis->get("string1");
var_dump($val); //输出val1

$redis->set("string1",4);
$redis->incr("string1",2);

$val_int=$redis->get("string1");
var_dump($val_int); //6

list类型操作


案例:list.php

<?php

$redis=new \Redis();

$redis->connect("127.0.0.1",7200);

//list 操作
$redis->delete("list1");

$redis->lpush("list1","A");
$redis->lpush("list1","B");
$redis->lpush("list1","C");

$val=$redis->rpop("list1");
var_dump($val);  //A

set类型操作


案例:set.php

$redis=new \Redis();

$redis->connect("127.0.0.1",7200);

//set操作
$redis->delete("set1");

$redis->sadd("set1","A");
$redis->sadd("set1","B");
$redis->sadd("set1","C");
$redis->sadd("set1","C");

$val=$redis->scard("set1");
var_dump($val); //3

$val=$redis->smembers("set1");
var_dump($val);
/*array(3) {
  [0]=>
  string(1) "C"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "A"
}*/

hash类型操作


案例:hash.php

<?php

$redis=new \Redis();

$redis->connect("127.0.0.1",7200);

//hash 操作
$redis->delete("driver1");

$redis->hset("driver1","name","mingming");
$redis->hset("driver1","age",25);
$redis->hset("driver1","gender",1);
$val=$redis->hget("driver1","name");
var_dump($val); //mingming

$val=$redis->hmget("driver1",array("name","age"));
var_dump($val);
/*
array(2) {
  ["name"]=>
  string(8) "mingming"
  ["age"]=>
  string(2) "25"
}
*/
sort set类型操作


案例:zset.php

<?php

$redis=new \Redis();

$redis->connect("127.0.0.1",7200);

//sort set 操作
$redis->delete("zset1");

$redis->zadd("zset1",100,"xaioming");//rank:2
$redis->zadd("zset1",90,"xiaohong");//rank:0
$redis->zadd("zset1",94,"xiaowang");//rank:1

$val=$redis->zrange("zset1",0,-1);//从低到高
var_dump($val);
/*
array(3) {
  [0]=>
  string(8) "xiaohong"
  [1]=>
  string(8) "xiaowang"
  [2]=>
  string(8) "xaioming"
}

*/
$val=$redis->zrevrange("zset1",0,-1);//从高到低
var_dump($val);
/*
array(3) {
  [0]=>
  string(8) "xaioming"
  [1]=>
  string(8) "xiaowang"
  [2]=>
  string(8) "xiaohong"
}
*/




发布了198 篇原创文章 · 获赞 68 · 访问量 96万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览