redis-缓存设计-统计最耗时API-用于性能优化和系统监控

 

 

原文来自:

    https://www.cnblogs.com/LQBlog/p/13367021.html

 

 

 redis-缓存设计-统计最耗时方法

    实现方式:

    1、使用ZSET作为统一入口,统计API的消耗时间

    2、ZSET的KEY是API,SCORE是API的访问时间

    3、使用ZSET的ZREVRANGEBYSCORE key max min获取有序集合中指定区间内的成员,通过分数从大到小排列。使用ZSET的ZREMRANGEBYRANK key  start stop移除有序集合中给定的排名区间的所有成员。

 

文章主目录   

 

    统计
    打印
    测试
    打印


统计

public static void addLog(Jedis conn, String methodName, Long startTime, Long endTime) {
        conn.zadd("timeLog", endTime - startTime, methodName);
        //只保留前2
        conn.zremrangeByRank("timeLog",0,-3);
    }

 


打印

  public static void   printTimeLog(Jedis conn){
        Set<Tuple> tuples= conn.zrevrangeWithScores("timeLog",0,-1);
        for (Tuple tuple:
                tuples) {
            System.out.println(tuple.getElement()+":"+tuple.getScore());
        }
    }

 

 

测试

 

 public static void main(String[] args)
            throws Exception {
        Jedis conn = new Jedis("127.0.0.1", 6379);
        conn.flushDB();
        test1(conn);
        test2(conn);
        test3(conn);
        printTimeLog(conn);
    }

    public static void test1(Jedis conn) throws InterruptedException {
        Long startTime = System.currentTimeMillis();
        Thread.sleep(1000);
        Long endTime = System.currentTimeMillis();
        addLog(conn, "test1", startTime, endTime);
    }

    public static void test2(Jedis conn) throws InterruptedException {
        Long startTime = System.currentTimeMillis();
        Thread.sleep(3000);
        Long endTime = System.currentTimeMillis();
        addLog(conn, "test2", startTime, endTime);
    }

    public static void test3(Jedis conn) throws InterruptedException {
        Long startTime = System.currentTimeMillis();
        Thread.sleep(10000);
        Long endTime = System.currentTimeMillis();
        addLog(conn, "test3", startTime, endTime);
    }

 


打印

test3:10003.0
test2:3005.0

 

posted @ 2021-11-26 18:37  dos_hello_world  阅读(213)  评论(0)    收藏  举报