出现上图的图形,就说明redis服务端开启成功,并且开启了密码功能(如果不加载配置文件,连接redis是不需要密码的,这样,会给我们的程序带来很大隐患)
密码的设置: 在redis配置文件中,搜索requirepass ,后面设置密码 比如 : requirepass G506myredis
则表示此redis服务端密码是G506myredis
1. 查询
根据sql语句到redis数据库中查询是否有相应的数据,如果有,则直接返回数据,如果没有,则到数据库查询数据返回给浏览器,并且将数据缓存到redis服务器
代码:
function inquiry_redis($sql)
{
//实例化redis对象
$redis = new Redis();
//连接redis
$redis->connect('localhost',6379);
//分配下面的任务密码权限
$redis->auth('G506myredis');
$key = md5($sql);
$data = $redis->get($key);//如果有data,此时应该是一个json字符串
if(!$data)
{
try{
$pdo = new PDO('mysql:dbname=test;host=localhost','root','root');
}catch(PDOException $e)
{
die("pdo连接失败:".$e->getMessage());
}
$stmt = $pdo->prepare($sql);
$stmt->execute();
$data = json_encode($stmt->fetchAll(2));//将从数据库取到的数据转化为json字符串(为了存储到redis中)
$redis->set($key,$data);
}
return json_decode($data);//返回数组格式的数据
}
$sql = 'select id,name,edu,city,salary from student';
var_dump(inquiry_redis($sql));
结果:
array (size=39)
0 =>
object(stdClass)[2]
public 'id' => '1' (length=1)
public 'name' => '周更生' (length=9)
public 'edu' => '大专' (length=6)
public 'city' => '山东省' (length=9)
public 'salary' => '5000.00' (length=7)
1 =>
object(stdClass)[3]
public 'id' => '2' (length=1)
public 'name' => '王小平' (length=9)
public 'edu' => '大专' (length=6)
public 'city' => '陕西省' (length=9)
public 'salary' => '500.00' (length=6)
2 =>
object(stdClass)[4]
public 'id' => '3' (length=1)
public 'name' => '周改娟' (length=9)
public 'edu' => '大专' (length=6)
public 'city' => '上海市' (length=9)
public 'salary' => '8000.00' (length=7)
3 =>
object(stdClass)[5]
public 'id' => '4' (length=1)
public 'name' => '高舸' (length=6)
public 'edu' => '高中' (length=6)
public 'city' => '山西省' (length=9)
(size=39)
0 =>
object(stdClass)[2]
public 'id' => '1' (length=1)
public 'name' => '周更生' (length=9)
public 'edu' => '大专' (length=6)
public 'city' => '山东省' (length=9)
public 'salary' => '5000.00' (length=7)
1 =>
object(stdClass)[3]
public 'id' => '2' (length=1)
public 'name' => '王小平' (length=9)
public 'edu' => '大专' (length=6)
public 'city' => '陕西省' (length=9)
public 'salary' => '500.00' (length=6)
2 =>
object(stdClass)[4]
public 'id' => '3' (length=1)
public 'name' => '周改娟' (length=9)
public 'edu' => '大专' (length=6)
public 'city' => '上海市' (length=9)
public 'salary' => '8000.00' (length=7)
3 =>
object(stdClass)[5]
public 'id' => '4' (length=1)
public 'name' => '高舸' (length=6)
public 'edu' => '高中' (length=6)
public 'city' => '山西省' (length=9)
第一次,从数据库取数据,将结果返回给浏览器,并将数据缓存到redis中
第二次,直接从redis中取数据,返回该浏览器
2. 删除
传进来一个sql,我们根据sql删除redis库中对应的key的数据
function delete_redis($sql)
{
//实例化redis对象
$redis = new Redis();
//连接redis
$redis->connect('localhost',6379);
//分配下面的任务密码权限
$redis->auth('G506myredis');
$key = md5($sql);
//删除对应的缓存的sql数据
$redis->del($key);
}
ps: 期待在这方面有丰富项目经验的phper提出更多的优化意见,谢谢