thinkphp6使用配置redis
2022-07-28 14:14:58
206
{{single.collect_count}}

使用composer安装 composer require predis/predis,.env加入如下配置:

[REDIS]HOST=127.0.0.1scheme=tcpPORT=6379CACHE_DB=0TOKEN_DB=1PASSWORD=admin

config下redis配置文件redis.php

<?php //Redis配置文件return ['scheme' => env('redis.scheme', 'tcp'),'host'=>env('redis.host', '127.0.0.1'),'port' => env('redis.port', '6379'), 'token' => env('redis.token_db', '1'), // token数据库:默认0~15个'cache' => env('redis.cache_db', '0'), // 缓存数据库 'password' => env('redis.password', ''), ];

直接使用

use Predis\Client;$redis = new Client(['scheme' => config('redis.scheme'),'host' => config('redis.host'),'port' => config('redis.port'),'cache' => config('redis.cache'),'password' => config('redis.password'),]);print_r($redis->set('test','123'));

封装服务类使用

<?phpnamespace common\Utils;use Predis\Client;class Redis{/** * 静态调用redis */public function __construct(){$this->redis = new Client(['scheme' => config('redis.scheme'),'host' => config('redis.host'),'port' => config('redis.port'),'cache' => config('redis.cache'),'password' => config('redis.password'),]);}/** * 如果不传入$host和$port默认读取Laravel环境变量的参数 * redis Set/setex封装,可直接传入数组,可设置过期时间 written:yangxingyi */public function set($key,$value,$expire=0,$host='',$port=''){if(!$key||!$value) return false;$host = $host?$host:getenv('REDIS_HOST');$port = $port?$port:getenv('REDIS_PORT');$value = is_array($value)?json_encode($value):$value;return $expire>0? $this->redis->setex(getenv('REDIS_PREFIX').$key, $expire,$value): $this->redis->set(getenv('REDIS_PREFIX').$key,$value);}/** * redis get封装,如果传入的是数组,返回的也是数组,同理字符串 written:yangxingyi */public function get($key,$host='',$port=''){$host = $host?$host:getenv('REDIS_HOST');$port = $port?$port:getenv('REDIS_PORT');$result =$this->redis->get(getenv('REDIS_PREFIX').$key);return is_null(json_decode($result))?$result:json_decode($result,true);}}
回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}