php获取redis对象数量,Php操作redis写入对象和查询对象

Php操作redis写入对象和查询对象

实体类Student.class.php

class Student

{

var $id;

var $sno;

var $sname;

public function getId()

{

return $this->id;

}

public function getSno()

{

return $this->sno;

}

public function getSname()

{

return $this->sname;

}

public function setId($id)

{

$this->id = $id;

}

public function setSno($sno)

{

$this->sno = $sno;

}

public function setSname($sname)

{

$this->sname = $sname;

}

}

?>

数据库操作对象DbStudent.class.php

class DbStudent

{

/*插入对象到redis中*/

function SaveStudent($redis,$db_index,$student)

{

$redis->select($db_index);

return $redis->set("student.".$student->GetId(),json_encode($student));

}

/*从redis中查询出对象*/

function LoadStudent($redis,$db_index,$key)

{

$redis->select($db_index);

return json_decode($redis->get("student.".$key));

}

}

?>

Redis连接类RedisDb.class.php

class RedisDb{

public $redis = null;

public function __construct(){

$this->redis = new Redis();

$this->redis->connect("127.0.0.1","6379");

}

/*

1--->必须处理此消息

0--->非必须处理.

*/

function PubUpdate($channel,$msg = "1")

{

$this->redis->publish($channel,$msg);

}

}

?>

类包含文件init.php

include("redisdb.class.php");

include("student.class.php");

include("DbStudent.class.php");

?>

测试文件test.sh

include('init.php');

$redisdb_obj = new RedisDb();

$dbstudent_obj = new DbStudent();

$student_obj = new Student();

$student_obj->setId(1);

$student_obj->setSno("001");

$student_obj->setSname("xiaoming");

/*插入数据

$result = $dbstudent_obj->SaveStudent($redisdb_obj->redis,0,$student_obj);

echo $result;*/

/*查询数据*/

$obj = $dbstudent_obj->LoadStudent($redisdb_obj->redis,0,"1");

echo $obj->id."
";

echo $obj->sno."
";

echo $obj->sname."
";

?>

首先执行插入操作,插入成功后会返回1,通过redis-cli能看到数据。

0818b9ca8b590ca3270a3433284dd417.png

然后执行查询操作,获取到数据:

0818b9ca8b590ca3270a3433284dd417.png

json_decode是将字符串转化为对象stdclass。该函数还有一个参数,第二个参数如果为true,就表示返回数组,而不是对象。

return json_decode($redis->get("student.".$key),true);

那么就需要将数组转化成对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值