Home > PHP Framework > ThinkPHP > Share records of Redis operation service classes in the TP6 framework

Share records of Redis operation service classes in the TP6 framework

藏色散人
Release: 2021-08-26 09:00:30
forward
3238 people have browsed it

The following is the thinkphp framework tutorial column to share with you the records of the Redis operation service class in ThinkPHP6. I hope it will be helpful to friends in need!

1. Define the service class

<?php

declare (strict_types=1);

namespace app\api\service\common;

use think\facade\Cache;

/**
 * 缓存服务
 * Class RedisService
 *
 * @package app\api\service\common
 */
class RedisService
{
    private $expire;
    private $expire_at;

    /**
     * 获取redis句柄
     *
     * @return object|null
     */
    public function client(): ?object
    {
        return Cache::store(&#39;redis&#39;)->handler();
    }

    /**
     * 处理缓存key(添加前缀...)
     *
     * @param string $key  key
     *
     * @return string
     */
    private function cacheKey(string $key): string
    {
        return Cache::getCacheKey($key);
    }

    /**
     * 缓存程序运行结果
     *
     * @param          $key
     * @param callable $callback
     * @param int      $expire
     *
     * @return mixed
     */
    public function cache($key, callable $callback, int $expire = 3600)
    {
        $cache = $this->client()->get($key);
        if (! $cache || ! unserialize($cache)) {
            $data = $callback();
            $this->client()->set($key, $cache = serialize($data), $expire);
        }

        return unserialize($cache);
    }

    /**
     * 程序运行锁
     * @param          $key
     * @param callable $callback
     * @param int      $timeout
     *
     * @return array
     */
    public function lock($key, callable $callback, int $timeout = 10): array
    {
        $lock = $this->client()->get($key);
        if ($lock) return ['code' => 0, 'data' => null];
        $this->client()->setex($key, $timeout, 1);
        $data = $callback();
        $this->client()->del($key);

        return ['code' => 1, 'data' => $data];
    }

    /**
     * 设置有效时间
     *
     * @param $ttl
     *
     * @return $this|false
     * @throws \Exception
     */
    public function setExpire($ttl)
    {
        if ($this->expire_at) throw new \Exception('setExpire and setExpireAt can not set both');
        $this->expire = $ttl;

        return $this;
    }

    /**
     * 设置到期时间
     *
     * @param $timestamp
     *
     * @return $this|false
     * @throws \Exception
     */
    public function setExpireAt($timestamp)
    {
        if ($this->expire > 0) throw new \Exception('setExpire and setExpireAt can not set both');
        $this->expire_at = $timestamp;

        return $this;
    }

    /**
     * 调用原生redis方法
     *
     * @return mixed
     */
    public function __call($name, $arguments)
    {
        $cache_key = $this->cacheKey($arguments[0]);

        $result = $this->client()->{$name}(...$arguments);

        // 设置过期时间
        $this->expire && $this->client()->expire($cache_key, $this->expire);
        $this->expire_at && $this->client()->expireAt($cache_key, $this->expire_at);

        return $result;
    }
}
Copy after login

2. Define the facade

<?php


namespace app\api\facade;


use app\api\service\common\RedisService;
use think\Facade;

/**
 * Class Redis
 *
 * @package app\api\facade
 *
 * @method static \Redis client()
 * @method static \Redis setExpire($ttl)
 * @method static \Redis setExpireAt($timestamp)
 * @method static mixed cache($key, callable $callback, int $expire = 3600)
 * @method static array lock($key, callable $callback, int $timeout = 10)
 */
class Redis extends Facade
{
    protected static function getFacadeClass()
    {
        return RedisService::class;
    }
}
Copy after login

3. How to use

3.1 Program lock

public function test()
    {
        $a = 1;
        $b = 2;
        $result = Redis::lock(&#39;lock:demo&#39;, function () use ($a, $b) {
            return $a + $b;
        }, 5);
        if ($result[&#39;code&#39;] == 0) return &#39;操作频繁,请稍后再试&#39;;
        return $result[&#39;data&#39;]; // 成功返回数据 3
    }
Copy after login

3.2 Method data cache

public function test()
{
    $a = 1;
    $b = 2;
    $result = Redis::cache(&#39;cache:demo&#39;, function () use ($a, $b) {
        return $a + $b;
    }, 5);

    return $result; // 成功返回数据 3,有效时长5秒
}
Copy after login

3.3 Simplified expiration time setting

// 24小时到期
Redis::setExpire(86400)->hSet('expire:demo', 'hash-key', 'hash-value');
// 2021-08-24 23:59:59到期
Redis::setExpireAt(strtotime('2021-08-24 23:59:59'))->hSet('expireAt:demo', 'hash-key', 'hash-value');
Copy after login

3.4 Normal call

// 普通调用,直接跟redis方法名
Redis::set('set:demo', 132456);
// idea支持代码提示调用
Redis::client()->set('set:demo', 132456);
Copy after login
Recommendation: "The latest 10 thinkphp video tutorials"

The above is the detailed content of Share records of Redis operation service classes in the TP6 framework. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template