TP6 프레임워크에서 Redis 운영 서비스 클래스 기록 공유

藏色散人
풀어 주다: 2021-08-26 09:00:30
앞으로
3135명이 탐색했습니다.

다음은 ThinkPHP6의 Redis 운영 서비스 수업 기록을 공유하는 thinkphp프레임워크 튜토리얼 칼럼입니다. 필요한 친구들에게 도움이 되었으면 좋겠습니다!

1. 서비스 클래스 정의

<?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;
    }
}
로그인 후 복사

2. 외관 정의

<?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;
    }
}
로그인 후 복사

3. 사용 방법

3.2 메소드 데이터 캐시

public function test()
    {
        $a = 1;
        $b = 2;
        $result = Redis::lock('lock:demo', function () use ($a, $b) {
            return $a + $b;
        }, 5);
        if ($result['code'] == 0) return '操作频繁,请稍后再试';
        return $result['data']; // 成功返回数据 3
    }
로그인 후 복사

3.3 단순화된 문제 시간 설정

아아아아

3.4 일반 통화

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

    return $result; // 成功返回数据 3,有效时长5秒
}
로그인 후 복사

추천: "

최신 10개 thinkphp 비디오 튜토리얼
"

위 내용은 TP6 프레임워크에서 Redis 운영 서비스 클래스 기록 공유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:learnku.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!