redis-缓存设计-统计max min sum count avg

统计方法

/**
     * 统计
     */
    public static  void  updateStats(Jedis conn,Integer productId,Integer value){
        String key="stats:"+productId;
        conn.zadd("minTemp",Double.valueOf(value),"min");
        conn.zadd("maxTemp",Double.valueOf(value),"max");
        ZParams minZParams=new ZParams();
        minZParams.aggregate(ZParams.Aggregate.MIN);
        ZParams maxZParams=new ZParams();
        maxZParams.aggregate(ZParams.Aggregate.MAX);
        //取并集 而不是交集和差集哦
        conn.zunionstore(key,minZParams,"minTemp",key);
        conn.zunionstore(key,maxZParams,"maxTemp",key);
        conn.zincrby(key,value,"sum");
        conn.zincrby(key,1,"count");
        //删除临时的key
        conn.del("minTemp");
        conn.del("maxTemp");
    }

 

打印统计

  public static void  printStats(Jedis conn,Integer productId){
        String key="stats:"+productId;
        Set<Tuple> tuples= conn.zrevrangeWithScores(key,0,-1);
        double sum=0;
        double avg=0;
        for (Tuple tuple:
        tuples) {
            if(tuple.getElement().equals("sum")){
                sum=tuple.getScore();
            }else if(tuple.getElement().equals("count")){
                avg=tuple.getScore();
            }
            System.out.println(tuple.getElement()+":"+tuple.getScore());
        }
        //计算平均值
        System.out.println("avg:"+avg);
    }

测试

 public static void main(String[] args)
            throws Exception {
        Jedis conn = new Jedis("127.0.0.1", 6379);
        conn.flushDB();
        for(int i=1;i<10;i++){
            updateStats(conn,1,i);
        }
        printStats(conn,1);
    }

打印:

sum:45.0
max:9.0
count:9.0
min:1.0
avg:9.0

 

posted @ 2020-07-23 15:35  意犹未尽  阅读(46)  评论(0编辑  收藏