thinkphp6使用配置redis

有目标就不怕路远。年轻人.无论你现在身在何方.重要的是你将要向何处去。只有明确的目标才能助你成功。没有目标的航船.任何方向的风对他来说都是逆风。因此,再遥远的旅程,只要有目标.就不怕路远。没有目标,哪来的劲头?一车尔尼雷夫斯基

导读:本篇文章讲解 thinkphp6使用配置redis,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

使用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 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'));

封装服务类使用

<?php

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


}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/134024.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!