thinkphp6使用配置redis

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

[REDIS]
HOST=127.0.0.1
scheme=tcp
PORT=6379
CACHE_DB=0
TOKEN_DB=1
PASSWORD=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 PredisClient;

        $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'));

封装服务类使用

<?php

namespace commonUtils;
use PredisClient;

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);
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值