本文主要研究一下如何使用RedisTemplate(lettuce类库)读取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);
    }
  • 这里使用lettuce的redisAsyncCommands的slowlogGet方法获取slowlog
  • 不过这里返回的是List<Object>,需要自己解析一下,具体详见下面的slowlog定义

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;
    }
}
  • 这里定义了slowlog的属性,其中还定义了从lettuce接口返回的Object的解析

小结

redisTemplate并没有提供现成的api来获取slowlog,因此需要通过execute方法获取底层的client实现,然后执行相关的操作来获取slowlog。

doc


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...