[case36]RedisTemplate读取slowlog

本文主要研究一下如何使用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
    原文地址: https://segmentfault.com/a/1190000016329337
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞