redis-快取設計-統計max min sum count avg
阿新 • • 發佈:2020-07-23
統計方法
/** * 統計 */ 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