由于目前站点统计某页面点击量(刷新也算入点击量),且每点击进入一次页面或刷新一次也没都会向点击量log表插入一条数据,所以该表日积月累的数据量必然很大,如果想根据该log查询最热门(及点击量最多的页面信息,则查询比较耗时)。也考虑过新建一张点击统计表,统计每个页面的点击次数,点击或刷新一次就在原来的基础上+1,但是又考虑到用redis缓存,也可以实现,且效率应该还不错。开始考虑使用redis 的SortedSet(有序集合)来实现(为了方便取 top 20),发现不可行。于是,redis Hash缓存页面相关信息走起~~~~~
代码如下:
#region 车辆点击量缓存 //获取所有竞拍的点击量 public static Dictionary<string, string> GetAllAuctionClicks() { var result = new Dictionary<string, string>(); if (!RedisSwitch) return result; try { var key = RedisKeyHelper.AllAuctionClicks(); using (var client = RedisManger.GetReadwriteClient()) { if (client.ContainsKey(key)) { result = client.GetAllEntriesFromHash(RedisKeyHelper.AllAuctionClicks()); } return result; } } catch (Exception ex) { return result; } } //设置所有竞拍的点击量 public static void SetAllAuctionClicks(Dictionary<string, string> clicksList) { if (!RedisSwitch) return; try { var key = RedisKeyHelper.AllAuctionClicks(); using (var client = RedisManger.GetReadwriteClient()) { if (client.ContainsKey(key)) { client.Remove(key); } client.SetRangeInHash(key, clicksList); } } catch (Exception ex) { return; } } //增加该AucId的点击次数 public static void IncrementAuctionClicks(int aucId) { if (!RedisSwitch)//开关关闭,则返回 return; try { var key = RedisKeyHelper.AllAuctionClicks(); using (var client = RedisManger.GetReadwriteClient()) { if (client.ContainsKey(key)) { if (client.HashContainsEntry(key, aucId.ToString())) //如果 该AucId在hash中,则对该AucId的次数加1,否则,加入一个新的Aucid,1 的key-value { client.IncrementValueInHash(key, aucId.ToString(), 1); } else { client.SetEntryInHash(key, aucId.ToString(), "1"); } } } } catch { } } //获取某一个aucid的点击次数 public static int GetAuctionClick(int aucId) { var result = 0; if (!RedisSwitch)//开关关闭,则返回 return result; try { var key = RedisKeyHelper.AllAuctionClicks(); using (var client = RedisManger.GetReadwriteClient()) { if (client.ContainsKey(key)) { if (client.HashContainsEntry(key, aucId.ToString())) //如果 该AucId在hash中,则取该AucId的点击次数,否则点击次数为0 { int.TryParse(client.GetValueFromHash(key, aucId.ToString()), out result); } } } } catch { return result; } return result; } #endregion