PHP 使用 Redis
用 phpredis 扩展或 Predis 在 PHP 里操作 Redis。
Key Pointsphpredis 是 C 扩展(快),Predis 是纯 PHP 库(易装);Laravel 缓存门面默认就接 Redis。
phpredis 示例
PHP
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('StrongPass!23');
$redis->set('user:1:name', 'alice');
$redis->incr('views');
echo $redis->get('user:1:name') . PHP_EOL;Output
aliceLaravel 缓存
PHP
// config/cache.php 设 default = 'redis'
Cache::put('user:1:name', 'alice', now()->addHour()); // 1 小时过期
echo Cache::get('user:1:name');PHP tears down after each request, so don't hold a Redis connection long in a script — close when done, or use the framework pool. For page caches, prefix keys and set TTLs per business so you can flush by prefix.
phpredis 示例
PHP
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('StrongPass!23');
$redis->set('user:1:name', 'alice');
$redis->incr('views');
echo $redis->get('user:1:name') . PHP_EOL;Output
aliceLaravel 缓存
PHP
// config/cache.php 设 default = 'redis'
Cache::put('user:1:name', 'alice', now()->addHour()); // 1 小时过期
echo Cache::get('user:1:name');PHP 请求结束进程就销毁,所以别在脚本里长占 Redis 连接——用完即关,或用框架的连接池。做页面缓存时给 key 加前缀并按业务设 TTL,方便统一清理。