ftuzlu/redis-cache-php

适用于PHP的通用Redis

1.0.0 2024-01-09 13:26 UTC

This package is auto-updated.

Last update: 2024-09-09 14:55:37 UTC


README

安装依赖项

composer require ftuzlu/redis-cache

建立Redis连接

  • 第一步是使用Connect类连接Redis
<?php
require_once('vendor/autoload.php');

use Fatihtuzlu\RedisCachePhp\Connection;
use Fatihtuzlu\RedisCachePhp\RedisCache;
use Predis\Client;

$connection = new Connection('tcp', '127.0.0.1', '6379');

$client = new Client();
$redisCache = new RedisCache($connection, $client);

$redisCache->set('example_key', 'Hello, Redis Cache!');

$val = $redisCache->getAllCachedData();
var_dump($val);

$value = $redisCache->get('example_key');
echo $value; // Output: Hello, Redis Cache!

$redisCache->delete('example_key'); //delete redis

缓存机制

  • 如果您想使用,可以启用缓存机制

缓存创建使用

  • 创建函数用于创建缓存
<?php

require_once('vendor/autoload.php');

$cacheInstance = new Symfony\Component\Cache\Simple\FilesystemCache();

$myCache = new Fatihtuzlu\CacheMecanism\Cache($cacheInstance);

$result = $myCache->create('new_key', 'New value', 3600);

记住缓存并检索数据

<?php

require_once('vendor/autoload.php');

$cacheInstance = new Symfony\Component\Cache\Simple\FilesystemCache();

$myCache = new Fatihtuzlu\CacheMecanism\Cache($cacheInstance);

$result = $myCache->remember('example_key', function () {
    echo 'Calculating result...' . PHP_EOL;
    return 42;
}, 60);

echo 'Result: ' . $result . PHP_EOL;

永久记住缓存并检索数据

<?php

require_once('vendor/autoload.php');

$cacheInstance = new Symfony\Component\Cache\Simple\FilesystemCache();

$myCache = new Fatihtuzlu\CacheMecanism\Cache($cacheInstance);

$result = $myCache->rememberForever('example_key', function () {
    echo 'Calculating result...' . PHP_EOL;
    return 42;
});

echo 'Result: ' . $result . PHP_EOL;

忘记缓存数据

<?php

require_once('vendor/autoload.php');

$cacheInstance = new Symfony\Component\Cache\Simple\FilesystemCache();

$myCache = new Fatihtuzlu\CacheMecanism\Cache($cacheInstance);

$result = $myCache->forget('new_key');