Thinkphp 3.2使用Redis

mac2022-06-30  23

(1)直接调用框架自带的Redis类:

路径:\ThinkPHP\Library\Think\Cache\Driver\Redis.class.php。

public function test(){ //创建一个redis对象 $redis = new \Redis(); //连接本地的 Redis 服务 $redis->connect('127.0.0.1', 6379); //密码验证,如果没有可以不设置 $redis->auth('123456'); //查看服务是否运行 echo "Server is running: " . $redis->ping(); echo '<br/>'; //设置缓存 $redis->set('username','zhang san',3600); //获取缓存 $user_name = $redis->get('username'); var_dump($user_name); }

运行结果:

Server is running: +PONG

string(9) "zhang san"


(2)使用S方法:

在配置文件中添加配置

'DATA_CACHE_TYPE' => 'Redis','REDIS_HOST' => '127.0.0.1','REDIS_PORT' => 6379,

一、redis不设置密码的情况下:

public function set_info(){ S('study','123'); } public function get_info(){ echo C('DATA_CACHE_TYPE'); echo '<br/>'; $a = S('study'); echo $a; }

先访问set_info,再访问get_info,返回结果:

Redis123

 

二、redis设置密码的情况下:

直接使用S方法,结果报错:

NOAUTH Authentication required.

然后添加设置 'REDIS_AUTH' => 123456,找到Redis类,发现没有设置密码,在Redis.class.php的__construct方法里添加代码:

然后再测试S方法: public function set_info(){ $a = S('study','1223'); var_dump($a); //true } public function get_info(){ echo C('DATA_CACHE_TYPE'); //Redis echo '<br/>'; $a = S('study'); echo $a; //1223 }

 


 

 

转载于:https://www.cnblogs.com/gyfluck/p/9244748.html

相关资源:Thinkphp 3.2框架使用Redis的方法详解
最新回复(0)