SoFunction
Updated on 2025-04-11

Implementation of real-time monitoring of Redis command flow in SpringBoot

Monitoring command flows helps us better understand the working state of Redis in daily use and debugging. Redis provides the MONITOR command, which can output command requests from all clients in Redis in real time, which is very helpful when debugging and analyzing performance. In the Spring Boot project, we can implement Redis command monitoring through the Jedis client. This article will introduce how to use Jedis to implement this function and compare how telnet implements the MONITOR mechanism.

The principle of Redis MONITOR command

MONITOR is a debugging command provided by Redis, which is used to output all commands sent by clients in real time. After MONITOR is started, Redis will continuously send each received command back to the requested client. This mechanism can help developers understand the running status of Redis and the execution of various commands in real time.

Usually used in the command linetelnetCome to executeMONITOR, to achieve continuous real-time output. And inJavaIn the client,JedisA similar monitoring function has been realized.

Use Jedis to implement Redis command monitoring

existSpring BootIn the project, we can useJedisProvidedmonitorMethod,RedisThe command stream is output to the console. The following is based onJedisMonitoring code example:

Add Jeids dependencies

Introduce Jedis dependencies to support Redis operations:

<dependency>
    <groupId></groupId>
    <artifactId>jedis</artifactId>
    <version>5.0.0</version> <!-- Please use the version that suits you -->
</dependency>

Implement Redis monitoring code

useApplicationRunnerThe interface can beSpring BootAutomatically execute when the project startsRedisMonitor threads. The following is the complete code implementation:

package ;

import .slf4j.Slf4j;
import ;
import ;
import ;
import ;
import ;

import ;

@Slf4j
@Service
public class RedisMonitorService implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) {
        // Start the monitoring thread        new Thread(this::monitorRedisCommands, "RedisMonitorThread").start();
    }

    /**
      * Continuously monitor Redis's command stream
      */
    private void monitorRedisCommands() {
        try (Jedis jedis = new Jedis("localhost", 6379)) { // Replace with your Redis address and port            ("Start monitor Redis command stream...");

            // Use JedisMonitor to listen to Redis commands            (new JedisMonitor() {
                @Override
                public void onCommand(String command) {
                    ("{} - {}", (), command);  // Print to console                }
            });
        } catch (Exception e) {
            ("An error occurred while monitoring Redis", e);
        }
    }
}

Detailed code explanation

  • runmethod:Spring BootIt will be automatically executed after startupmonitorRedisCommandsMethod, continuously monitor through independent threadsRedisCommand flow.
  • monitorRedisCommandsMethod: This method is createdJedisClient and executemonitorMethod, start monitoringRedisAll commands.
  • JedisMonitorInterface:JedisProvidedJedisMonitorIn the interface,onCommandThe callback will be fired every time a Redis command is received. Here we output the command to the console for real-time viewing.

The principle of Jedis monitor implementation

JedisofmonitorThe bottom layer of the method is not a traditional while loop, but usesRedisThe command flow mechanism of the protocol. Specifically,Jedis monitorDepend onRedisContinuous connection, read each command through the InputStream stream. Here are the key implementation steps of Jedis monitor:

  1. sendMONITOROrder:()WillMONITORCommand sent toRedisServer, enable real-time monitoring.

  2. Waiting for a response:()Used for receivingRedisReturnedOKStatus code, indicatingMONITORThe order has taken effect.

  3. Continuous reading stream: through(connection)Start upRedisContinuous monitoring of response.proceedMethod internal useInputStreamStreaming reading, continuous receptionRedisEach command log sent and triggersonCommandCallback.

This mechanism is commonwhileDifferent loops: traditional loops will actively read data every time the condition is met, andInputStreamThe continuous connection mechanism is similartelnet, can passively receive continuous output from the server.

Use while loop to simulate the MONITOR command

Although Jedis's monitor mechanism is very efficient, there is noJedisMonitorIf supported, you can passwhileCycle manual pollingRedisThe command output is used to implement continuous listening. The following is a pseudo-code example, which simulateswhile Circular monitoraccomplish:

// Pseudocode: Use a while loop to continuously read Redis command logspublic void monitorWithWhileLoop() {
    try (Jedis jedis = new Jedis("localhost", 6379)) { // Replace with your Redis address and port        // Send the MONITOR command to start monitoring        ();

        // Loop to read each command returned by Redis        while (true) {
            String commandLog = ().getBulkReply();
            (commandLog); // Print each command        }
    } catch (Exception e) {
        ();
    }
}

Jedis monitor vs while loop vs telnet

Implementation method describe advantage shortcoming
Jedis monitor Continuously receive Redis logs using streaming connections Continuous reception, high efficiency Rely on Jedis's underlying implementation, not easy to customize
while loop Active polling Redis, non-monitor mode Suitable for simple query Real-time monitoring cannot be truly achieved, low efficiency
telnet CLI continues to connect and receive Redis logs Easy to debug, lightweight Applicable only to command line, not to program calls

Running effect

start upSpring BootAfter the project,RedisThe command stream will be automatically output to the console, with the following effects:

2023-04-01 10:00:00 - SET key1 value1
2023-04-01 10:00:02 - GET key1
2023-04-01 10:00:05 - DEL key1

As you can see, each command is timestamped and printed to the console. This is for debugging and analysisRedisThe frequency of command execution is very helpful.

Summarize

The Redis MONITOR command can output command logs of all clients in real time, and is a powerful tool for debugging and analyzing Redis performance. In Spring Boot projects, you can use Jedis's monitor method to achieve this function. Jedis's monitor is not a simple while loop, but a command stream similar to telnet continuously listening to Redis, which can efficiently process large amounts of logs. This mechanism is suitable for development and testing environments, but it requires attention to performance overhead to avoid running for a long time in a production environment.

The above is the detailed content of real-time monitoring of Redis command streams in SpringBoot. For more information about SpringBoot monitoring of Redis command streams, please pay attention to my other related articles!