RedisTemplate讀取slowlog

go4it發表於2018-09-09

本文主要研究一下如何使用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,需要自己解析一下,具體詳見下面的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

相關文章