thinkphp5.1使用redis缓存

tp5.1出来已经挺久的了,这边记录下tp5.1该怎么使用redis缓存。

安装好redis服务器,php的redis扩展phpredis(https://github.com/phpredis/phpredis#hexists


window安装扩展,可以参考我的另一篇文章:
https://www.jianshu.com/p/b2ba1c565148

tp设置配置

配置很简单,只需要修改config/cache.php为:

return [
    'type' => 'complex',
    // 默认
    'default' => [
        // 驱动方式
        'type'   => 'File',
        // 缓存保存目录
        'path'   => '',
        // 缓存前缀
        'prefix' => '',
        // 缓存有效期 0表示永久缓存
        'expire' => 0,
    ],
    // 文件
    'file' => [
        // 驱动方式
        'type'   => 'File',
        // 缓存保存目录
        'path'   => '',
        // 缓存前缀
        'prefix' => '',
        // 缓存有效期 0表示永久缓存
        'expire' => 0,
    ],
    // redis
    'redis' =>  [
        'type'       => 'redis',
        'host'       => '127.0.0.1',
        'port'       =>  '6379',
        'password'   => '',
        // 全局缓存有效期(0为永久有效)
        'expire'     =>  0,
        // 缓存前缀
        'prefix'     =>  '',
    ],
];

这样,cache就支持文件和redis两种缓存方式了。

使用redis来存储缓存数据:

// 使用文件缓存
Cache::set('name','value',3600);
Cache::get('name');
// 使用Redis缓存
Cache::store('redis')->set('name','value',3600);
Cache::store('redis')->get('name');
// 切换到文件缓存
Cache::store('default')->set('name','value',3600);
Cache::store('default')->get('name');

使用redis的类方法操作

tp5.1的Cache类提供了一个方法,可以返回缓存类型的实例,这样就可以使用Redis类的缓存了

$redis = Cache::store('redis')->handler();
返回的为Redis对象,这样就可以使用Redis类里面的方法来操作redis缓存了。



phpredis扩展提供的方法参考:
https://github.com/phpredis/phpredis#hexists

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转自:http://bbs.redis.cn/forum.php?mod=viewthread&tid=481 p...
    木十2036阅读 4,386评论 0 7
  • phpredis是php的一个扩展,效率是相当高有链表排序功能,对创建内存级的模块业务关系 很有用;以下是redi...
    神秘者007阅读 5,130评论 0 1
  • PHP-redis中文文档 phpredis是php的一个扩展,效率是相当高有链表排序功能,对创建内存级的模块业务...
    神秘者007阅读 7,664评论 0 2
  • Redis::__construct构造函数$redis = new Redis(); connect, open...
    bycall阅读 5,298评论 0 2
  • phpredis是PHP的一个扩展,效率是相当高有链表排序功能,对创建内存级的模块业务关系很有用;以下是redis...
    史史小子阅读 2,642评论 0 2