Redis cache context listener in spring boot how to know is redis cache up or not?

1.7k Views Asked by At

We have a spring application where redis cache has been implemented along with the database MySQL. Here we are using redis cache to store the temporary values for the server validations instead of hitting the database every time, hence hitting the database calls every time gets reduces system performance.

Now i explain my problem while hitting the spring boot action endpoints, if suddenly my redis cache server stops, we would like to know how to get the notification that my redis cache server is down. So we need solution / example java application to get the notification using redis cache listener context or anything like that.

1

There are 1 best solutions below

0
On

Redis doesn't work that way. In fact, no remote service will notify your application that it's down. Usually, it's the other way round: If the service you're consuming is accessed with a more or less sophisticated client, you might take advantage of the client's features.

Asynchronous clients that run I/O, or monitoring threads can help here. More specific, it depends on the client you're using with Spring Boot and Redis. Jedis is a plain client that reacts on a request basis. Lettuce allows you to register a RedisConnectionStateListener that is called on specific connection events, such as connected/disconnected:

RedisClient redisClient = …;

redisClient.addListener(new RedisConnectionStateListener() {
    @Override
    public void onRedisConnected(RedisChannelHandler<?, ?> redisChannelHandler) {

    }

    @Override
    public void onRedisDisconnected(RedisChannelHandler<?, ?> redisChannelHandler) {

    }

    @Override
    public void onRedisExceptionCaught(RedisChannelHandler<?, ?> redisChannelHandler, Throwable throwable) {

    }
});

When using Spring Data Redis, retrieving the RedisClient from LettuceConnectionFactory might be a bit tricky as it is a private field. Hence it requires reflection.