use think\facade\Cache;

class RedisCache
{
    public function remember($key, $time, $callback)
    {
        $value = Cache::store('redis')->get($key);
        if (!$value) {
            $value = $callback();
            Cache::store('redis')->set($key, $value, $time);
        }
        return $value;
    }
}

使用ThinkPHP中的缓存模块可以轻松地实现对Redis缓存的集成。以上示例演示了如何使用Redis缓存,在缓存中存储指定时间的数据。

use think\facade\Cache;

class ExampleController extends Controller
{
    public function index()
    {
        $data = (new RedisCache())->remember('example-key', 3600, function () {
            // 执行查询、计算等耗时操作
            $result = Model::where('condition', 'value')->select();
            return $result;
        });

        return view('index', ['data' => $data]);
    }
}

在控制器中,我们可以通过调用自定义的remember方法来获取Redis缓存中的数据。如果缓存中不存在该数据,则会执行传入的回调函数,并将计算后的结果存储到缓存中。下次再调用remember方法时,将直接返回缓存中的数据,避免重复计算。

通过合理使用ThinkPHP中的缓存模块,我们可以提升系统的性能和响应速度,更好地优化我们的应用程序。