上代码
<?php
class RedisDB {
private $redis;
function __construct($host, $port, $password = '') {
$this->redis = new Redis();
$this->redis->connect($host, $port);
$password && $this->redis->auth($password); // 增加连接密码
}
// 设置值
public function set($key, $value, $expire = 0) {
if ($expire > 0) {
return $this->redis->setex($key, $expire, $value);
} else {
return $this->redis->set($key, $value);
}
}
// 获取值
public function get($key) {
return $this->redis->get($key);
}
// 删除值
public function delete($key) {
return $this->redis->delete($key);
}
// 判断 key 是否存在
public function exists($key) {
return $this->redis->exists($key);
}
// 自增
public function increment($key) {
return $this->redis->incr($key);
}
// 自减
public function decrement($key) {
return $this->redis->decr($key);
}
// 切换数据库
public function select($db) {
return $this->redis->select($db);
}
// 释放连接资源
public function __destruct() {
$this->redis->close();
}
}
//使用示例
//连接Redis
$redis = new RedisDB('127.0.0.1', 6379);#若有密码,请在第3个参数增加密码
//选择数据库
$redis->select(1);#数据库一般是0,1,2,4,5..............
// 设置值
$redis->set('name', 'Tom');
// 获取值
$name = $redis->get('name');
// 自增
$redis->increment('counter');
// 自减
$redis->decrement('counter');
// 删除值
$redis->delete('name');