Laravel Passport 使用缓存优化记录

Laravel框架
413
0
0
2022-04-10
标签   Laravel缓存

由于 Passport 不停的查询数据库, 为了那些性能, 从而使用redis进行缓存

特将修改的过程记录一下. 如有不对的地方, 欢迎各位能够指出错误

  1. 新增一个 ClientRepository 继承于 Laravel\Passport\ClientRepository 改写 find() 方法
<?php


namespace App\Repositories;

use Illuminate\Support\Facades\Cache;
use Laravel\Passport\ClientRepository AS BaseClientRepository;
use Laravel\Passport\Passport;

class ClientRepository extends BaseClientRepository
{
    /**
     * Get a client by the given ID.
     *
     * @param  int  $id
     * @return \Laravel\Passport\Client|null
     */ 
    public function find($id)
    {
        return Cache::remember("passport:client:{$id}", 86400, 
            function () use ($id) {
                $client = Passport::client();
                return $client->where($client->getKeyName(), $id)->first();
            }
        );
    }
}
  1. 新增一个 TokenRepository 继承于 Laravel\Passport\TokenRepository 改写 find() 方法
<?php


namespace App\Repositories;

use Illuminate\Support\Facades\Cache;
use Laravel\Passport\Passport;
use Laravel\Passport\TokenRepository AS BaseTokenRepository;

class TokenRepository extends BaseTokenRepository
{
    /**
     * Get a token by the given ID.
     *
     * @param  string  $id
     * @return \Laravel\Passport\Token
     */ 
    public function find($id)
    {
        return Cache::remember("passport:token:{$id}", 86400, 
            function () use ($id) {
                return Passport::token()->where('id', $id)->first();
            }
        );
    }
}
  1. App\Providers 新增 PassportServiceProvider
<?php

namespace App\Providers;

use App\Repositories\ClientRepository;
use App\Repositories\TokenRepository;
use Laravel\Passport\PassportServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;

class PassportServiceProvider extends ServiceProvider
{

    /**
     * Register the service provider.
     *
     * @return void
     */ 
    public function register()
    {
        $this->registerTokenRepository();

        parent::register();
    }

    /**
     * Register the client repository.
     *
     * @return void
     */ 
    protected function registerClientRepository()
    {
        $this->app->singleton('Laravel\Passport\ClientRepository', function ($container) {
            $config = $container->make('config')->get('passport.personal_access_client');
            return new ClientRepository($config['id'] ?? null, $config['secret'] ?? null);
        });
    }

    /**
     * Register the client repository.
     *
     * @return void
     */ 
    protected function registerTokenRepository()
    {
        $this->app->singleton('Laravel\Passport\TokenRepository', function ($container) {
            return new TokenRepository();
        });
    }

}
  1. config/app.phpproviders 添加 App\Providers\PassportServiceProvider::class 后就可以使用redis进行数据缓存了

关于其他的操作, 请根据自己的实际情况去处理, 当前只做最简单的缓存操作.