Redis是一款使用内存作为存储介质的数据库。大家应该都知道,计算机最快的单元是CPU,较次之的单元就是内存,再其次才是固态硬盘,最后是传统的物理硬盘。
现如今大部分笔记本电脑和台式机都已经开始采用固态硬盘作为主要存储介质了,但是服务器领域传统的物理硬盘还是主流的(毕竟几百G、甚至几个T的巨大容量固态硬盘成本太高了)。所以,Redis作为一种使用内存来存储数据的数据库,追求的目标就是一个字——快,我们可以通过将“热”数据放入Redis来大幅度提高数据的读写性能,而“冷”数据放在物理硬盘上面保存。
福哥今天就要建立一个TFRedis操作对象用来操作Redis数据库,把这个TFRedis操作对象加入到我们的TFPHP框架里面,使框架支持对Redis的操作。
private function connect(){
if($this->redis != null){
return;
}
$this->host = $this->params['host'];
$this->port = $this->params['port'];
$this->pwd = $this->params['pass'];
$this->db = $this->params['db'];
if($this->host == null){
$this->host = "localhost";
}
if($this->port == null){
$this->port = 6379;
}
if($this->pwd == null){
$this->pwd = "";
}
if($this->db == null){
$this->db = "test";
}
try{
// connect
$this->redis = new \Redis();
$this->redis->connect($this->host, $this->port);
// auth
if($this->pwd != ""){
$this->redis->auth($this->pwd);
}
}
catch(\RedisException $e){
throw $e;
}
}public function get(string $key):?string {
try{
// connect
$this->connect();
$value = $this->redis->get($this->db. $key);
if($value !== false){
return $value;
}
}
catch(\RedisException $e){
$this->lastErrcode = $e->getCode();
$this->lastErrmsg = $e->getMessage();
}
return null;
}public function set(string $key, string $value):bool {
try{
// connect
$this->connect();
$ret = $this->redis->set($this->db. $key, $value);
if($ret !== false){
return true;
}
}
catch(\RedisException $e){
$this->lastErrcode = $e->getCode();
$this->lastErrmsg = $e->getMessage();
}
return false;
}public function expire(string $key, int $timeout):bool {
try{
// connect
$this->connect();
$ret = $this->redis->expire($this->db. $key, $timeout);
if($ret !== false){
return true;
}
}
catch(\RedisException $e){
$this->lastErrcode = $e->getCode();
$this->lastErrmsg = $e->getMessage();
}
return false;
}public function delete(string $key):bool {
try{
// connect
$this->connect();
$ret = $this->redis->delete($this->db. $key);
if($ret !== false){
return true;
}
}
catch(\RedisException $e){
$this->lastErrcode = $e->getCode();
$this->lastErrmsg = $e->getMessage();
}
return false;
}TFRedis存储于TFPHP\Database\NoSQL\TFRedis.inc.php里面,它将Redis原生对象封装了起来。由于Redis本身没有数据库的概念,所以TFRedis增加了一个伪数据库的概念,这样可以区分不同项目里面的同名数据的冲突问题。
初始化Redis对象,建立Redis连接,如果有密码就使用密码认证一下。
使用Redis对象的set方法写入一个数据到Redis里。
使用Redis对象的get方法从Redis里读取一个数据。
使用Redis对象的expire方法设置一个数据的有效期。
使用Redis对象的delete方法删除一个数据。
直接取数据tfphp,因为没有写过肯定是空的,然后写入数据tfphp,此时有了数据。
接着设置数据tfphp在6秒后过期,使用sleep登上7秒,此时数据没有了
最后设置数据tfphp,使用delete删除数据tfphp,此时数据没有了

今天福哥带着童鞋们完成了TFRedis对象功能的实现,使用TFRedis就可以操作Redis数据库了。在前面的教程里面福哥已经交给大家在TFLinux虚拟机里面安装了Redis数据库服务器了,今后我们开发项目里就可以使用Redis进行项目性能的优化了。