Kotchasan Framework Documentation
Kotchasan\Cache\RedisCache
Kotchasan\Cache\RedisCache
RedisCache เป็นระบบ Cache ที่เก็บข้อมูลใน Redis server ทำให้สามารถ share ข้อมูลข้าม requests และข้ามหลาย processes ได้
สารบัญ
ภาพรวม
RedisCache มีคุณสมบัติดังนี้:
- Persistent: ข้อมูลยังคงอยู่แม้ script จบการทำงาน
- Distributed: สามารถ share cache ระหว่างหลาย servers
- Fast: Redis เป็น in-memory database ที่รวดเร็ว
- Feature Rich: รองรับ TTL, prefix, และ statistics
ความต้องการ:
- Redis server
- phpredis extension
เมื่อไหร่ควรใช้:
- ต้องการ cache ที่ persist ข้าม requests
- ต้องการ share cache ระหว่างหลาย application servers
- มีข้อมูลจำนวนมากที่ต้องการ cache
การติดตั้งและใช้งาน
ความต้องการระบบ
- PHP 7.4 หรือสูงกว่า
- Redis server (4.0+)
- phpredis extension
การติดตั้ง phpredis
# Ubuntu/Debian
sudo apt-get install php-redis
# CentOS/RHEL
sudo yum install php-redis
# หรือผ่าน PECL
pecl install redisการใช้งานพื้นฐาน
use Kotchasan\Cache\RedisCache;
// สร้าง instance พร้อมเชื่อมต่อ Redis
$cache = new RedisCache(
'127.0.0.1', // host
6379, // port
null, // password (null = ไม่มี)
0, // database number
'myapp_', // key prefix
3600 // default TTL
);
// บันทึก cache
$cache->set('user:1', ['name' => 'John', 'email' => 'john@example.com']);
// ดึง cache
$userData = $cache->get('user:1');
// Result: ['name' => 'John', 'email' => 'john@example.com']เมธอดหลัก
__construct()
สร้าง instance และเชื่อมต่อ Redis
Signature:
public function __construct(
string $host = '127.0.0.1',
int $port = 6379,
?string $password = null,
int $database = 0,
string $prefix = 'kotchasan_',
int $defaultTtl = 3600
)Parameters:
$host- Redis server host$port- Redis server port$password- Password สำหรับ authentication (optional)$database- Database number (0-15)$prefix- Prefix สำหรับทุก keys$defaultTtl- TTL เริ่มต้น (วินาที)
connect()
เชื่อมต่อ Redis server
Signature:
public function connect(): boolReturns: true ถ้าเชื่อมต่อสำเร็จ
get()
ดึงค่าจาก cache
Signature:
public function get(string $key, $default = null)set()
บันทึกค่าลง cache
Signature:
public function set(string $key, $value, ?int $ttl = null): booldelete()
ลบ cache item
Signature:
public function delete(string $key): boolclear()
ล้าง cache ทั้งหมด (เฉพาะ keys ที่มี prefix)
Signature:
public function clear(): boolhas()
ตรวจสอบว่ามี key อยู่ใน cache หรือไม่
Signature:
public function has(string $key): boolisAvailable()
ตรวจสอบว่า Redis พร้อมใช้งานหรือไม่
Signature:
public function isAvailable(): boolgetStats()
ดึงสถิติการใช้งาน
Signature:
public function getStats(): arrayReturns:
[
'hits' => 1500,
'misses' => 200,
'writes' => 1000,
'connected' => true,
'server_info' => [...] // ข้อมูลจาก Redis INFO
]getRedis()
ดึง Redis connection สำหรับใช้งานโดยตรง
Signature:
public function getRedis(): ?\Redisclose()
ปิด connection
Signature:
public function close(): voidตัวอย่างการใช้งาน
1. Session Store
use Kotchasan\Cache\RedisCache;
class SessionStore
{
private RedisCache $cache;
public function __construct()
{
$this->cache = new RedisCache(
'localhost', 6379, null, 0,
'session_',
1800 // 30 minutes
);
}
public function save(string $sessionId, array $data): bool
{
return $this->cache->set($sessionId, $data);
}
public function load(string $sessionId): ?array
{
return $this->cache->get($sessionId);
}
public function destroy(string $sessionId): bool
{
return $this->cache->delete($sessionId);
}
public function refresh(string $sessionId): bool
{
$data = $this->load($sessionId);
if ($data) {
return $this->save($sessionId, $data);
}
return false;
}
}2. Rate Limiting
use Kotchasan\Cache\RedisCache;
class RateLimiter
{
private RedisCache $cache;
private int $maxRequests;
private int $windowSeconds;
public function __construct(int $maxRequests = 100, int $windowSeconds = 60)
{
$this->cache = new RedisCache(
'localhost', 6379, null, 0,
'rate_',
$windowSeconds
);
$this->maxRequests = $maxRequests;
$this->windowSeconds = $windowSeconds;
}
public function isAllowed(string $identifier): bool
{
$key = "limit_{$identifier}";
$current = $this->cache->get($key, 0);
if ($current >= $this->maxRequests) {
return false;
}
$this->cache->set($key, $current + 1, $this->windowSeconds);
return true;
}
public function getRemainingRequests(string $identifier): int
{
$key = "limit_{$identifier}";
$current = $this->cache->get($key, 0);
return max(0, $this->maxRequests - $current);
}
}
// การใช้งาน
$limiter = new RateLimiter(100, 60);
$clientIp = $_SERVER['REMOTE_ADDR'];
if (!$limiter->isAllowed($clientIp)) {
http_response_code(429);
die('Too Many Requests');
}3. การใช้งานกับ CacheFactory
use Kotchasan\Cache\CacheFactory;
// สร้าง RedisCache ผ่าน Factory
$cache = CacheFactory::create([
'driver' => 'redis',
'host' => '127.0.0.1',
'port' => 6379,
'password' => 'secret',
'database' => 0,
'prefix' => 'myapp_'
]);
// ใช้งานเหมือน cache ทั่วไป
$cache->set('key', 'value', 3600);4. Caching Database Queries
use Kotchasan\Cache\RedisCache;
use Kotchasan\Database;
class UserRepository
{
private RedisCache $cache;
private Database $db;
public function __construct()
{
$this->cache = new RedisCache('localhost', 6379, null, 0, 'users_', 600);
$this->db = Database::create();
}
public function findById(int $id): ?array
{
$key = "user_{$id}";
// ลอง cache ก่อน
$user = $this->cache->get($key);
if ($user !== null) {
return $user;
}
// Query จาก database
$user = $this->db->select('*')
->from('users')
->where('id', '=', $id)
->first();
if ($user) {
$this->cache->set($key, (array)$user);
}
return $user ? (array)$user : null;
}
public function invalidate(int $id): bool
{
return $this->cache->delete("user_{$id}");
}
}Best Practices
1. ใช้ Prefix ที่มีความหมาย
// แยก prefix ตาม feature
$userCache = new RedisCache('localhost', 6379, null, 0, 'user_');
$sessionCache = new RedisCache('localhost', 6379, null, 0, 'session_');
$apiCache = new RedisCache('localhost', 6379, null, 0, 'api_');2. ตรวจสอบ Connection ก่อนใช้
$cache = new RedisCache('localhost', 6379);
if (!$cache->isAvailable()) {
// Fallback to MemoryCache
$cache = new MemoryCache();
}3. จัดการ Error
try {
$cache = new RedisCache('localhost', 6379);
$result = $cache->get('key');
} catch (\Exception $e) {
// Log error and use fallback
error_log("Redis error: " . $e->getMessage());
$result = null;
}ข้อควรระวัง
⚠️ Warning:
- ตรวจสอบให้แน่ใจว่า Redis server ทำงานอยู่
- ใช้ password สำหรับ production
- ระวังการใช้
clear()ใน shared environment💡 Tip: ใช้ Redis Cluster สำหรับ high availability
คลาสที่เกี่ยวข้อง
- CacheFactory - สร้าง cache instances
- [FileCache] - Cache แบบไฟล์
- MemoryCache - Memory Cache
- QueryCache - Cache สำหรับ Query