如何检查 Redis 服务器是否正在运行?
如果它没有运行,我想回退到使用数据库。
我正在使用 FuelPHP 框架,因此我愿意接受基于此的解决方案,或者只是标准 PHP。
您可以使用命令行来确定 redis 是否正在运行:
redis-cli ping
你应该回来
PONG
这表明 redis 已启动并正在运行。
您可以做的是尝试获取一个实例 (\Redis::instance()) 并像这样使用它:
try
{
$redis = \Redis::instance();
// Do something with Redis.
}
catch(\RedisException $e)
{
// Fall back to other db usage.
}
但最好你知道 redis 是否正在运行。这只是动态检测它的方法。
redis-cli -h host_url -p 6379 ping
你可以这样做。
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
echo $redis->ping();
然后检查它是否打印+PONG
,这表明 redis-server 正在运行。
所有的答案都很棒,
a另一种方法是检查if default REDIS port is listening
即端口号 6379
lsof -i:6379
如果您没有得到上述命令的任何输出,则表示 redis 没有运行。
这适用于那些运行Node-Redis的人。
const redis = require('redis');
const REDIS_PORT = process.env.REDIS_PORT || 6379
const client = redis.createClient(REDIS_PORT)
const connectRedis = async () => {
await client.PING().then(
async () => {
// what to run if the PING is successful, which also means the server is up.
console.log("server is running...")
},
async () => {
// what to run if the PING is unsuccessful, which also means the server is down.
console.log("server is not running, trying to connect...")
client.on('error', (err) => console.log('Redis Client Error', err));
await client.connect();
})
return
}