PHP 使用 Redis

用 phpredis 扩展或 Predis 在 PHP 里操作 Redis。

Beginner
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
alice

Laravel 缓存

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.

Friends & Partners