[case36] reistemplate reads slowlog

  redis

Order

This article focuses on how to use RedisTemplate (Lettuce class library) read slowlog

maven

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.3</version>
        </dependency>

redisAsyncCommands.slowlogGet

    @Test
    public void testGetSlowlog(){
        List<Object> slowlogs = redisTemplate.execute(new RedisCallback<List<Object>>() {
            @Override
            public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
                System.out.println(connection.getClass());
                RedisAsyncCommands redisAsyncCommands = (RedisAsyncCommands) connection.getNativeConnection();
                RedisFuture<List<Object>> future = redisAsyncCommands.slowlogGet(10);
                try {
                    return future.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });

        List<Slowlog> result = slowlogs.stream()
                .map(e -> Slowlog.from(e))
                .collect(Collectors.toList());
        System.out.println(result);
    }
  • Here, the slowlog is obtained by using lettuce’s redisAsyncCommands’ slowlogGet method.
  • However, what is returned here is List<Object >, which needs to be parsed by itself. please refer to the following slowlog definition for details.

slowlog

@Data
@Builder
public class Slowlog {

    private long id;
    private long timeStamp;
    private long executionTime;
    private List<String> args;

    @Tolerate
    public Slowlog() {
    }

    public static Slowlog from(Object object){
        List data = (List)object;
        List<byte[]> args = (List<byte[]>) data.get(3);
        Slowlog slowlog = Slowlog.builder()
                .id(Long.parseLong(data.get(0).toString()))
                .timeStamp(Long.parseLong(data.get(1).toString()))
                .executionTime(Long.parseLong(data.get(2).toString()))
                .args(args.stream().map(e -> new String(e)).collect(Collectors.toList()))
                .build();
        return slowlog;
    }
}
  • Here, the attribute of slowlog is defined, and the resolution of Object returned from lettuce interface is also defined.

Summary

RedisTemplate does not provide a ready-made api to obtain slowlog, so the underlying client implementation needs to be obtained through the execute method, and then relevant operations need to be performed to obtain slowlog.

doc