How to check whether the Redis server is running
PhpFuelphpPhp Problem Overview
How to check whether the Redis server is running?
If it's not running, I want to fallback to using the database.
I'm using the FuelPHP framework, so I'm open to a solution based on this, or just standard PHP.
Php Solutions
Solution 1 - Php
You can use command line to determine if redis is running:
redis-cli ping
you should get back
PONG
that indicates redis is up and running.
Solution 2 - Php
What you can do is try to get an instance (\Redis::instance()) and work with it like this:
try
{
$redis = \Redis::instance();
// Do something with Redis.
}
catch(\RedisException $e)
{
// Fall back to other db usage.
}
But preferably you'd know whether redis is running or not. This is just the way to detect it on the fly.
Solution 3 - Php
redis-cli -h host_url -p 6379 ping
Solution 4 - Php
All answers are great,
aAnother way can be to check if default REDIS port is listening
i.e port number 6379
lsof -i:6379
if you don't get any output for above command then it implies redis is not running.
Solution 5 - Php
you can do it by this way.
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
echo $redis->ping();
and then check if it print +PONG
, which show redis-server is running.
Solution 6 - Php
This is for those running 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
}