本文实例讲述了thinkphp 3.2框架使用redis的方法。分享给大家供大家参考,具体如下:

(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,返回结果:

redis
123

二、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
  }