利用redis统计分布式集群中接口缓存命中情况

接口使用了缓存,想看看缓存命中率,到底提升了多少了?固想到做个统计方法,单机情况下使用 AtomicImteger,考虑到分布式集群中多台服务器调用,所以考虑使用redis进行统计 原来的想法很简单用分布式锁  控制每次只有一个线程进行操作,但是需要进行获取数据 数据+1 再进行数据放入 三步过程 没有获取到锁的线程 进行等待后重试获取锁 但是此种情况会出现某些线程饿死,为了防止线程饿死又要做成 重试次数限制 超过次数就放弃统计 这种统计出来会使的大体趋势是正确的,数字会有偏差.机制需要考虑 ,就一个统计方法不想废太多脑细胞,所以pass此方案 看到redis自己有RedisAtomicLong 这个所以考虑使用这个去做.
直接甩代码

/**

		* @Title: incrementAndGet 
	* @Description: 计数+1
	* @param @param redisTemplate
	* @param @param key    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	private static void incrementAndGet (String key) {
		  ExecutorService es = Executors.newFixedThreadPool(1);
		  try {
			  es.execute(new Runnable() {
					
					@SuppressWarnings("unchecked")
					@Override
					public void run() {
						 boolean flag = false;
						 RedisTemplate<Serializable, Serializable> redisTemplate = (RedisTemplate<Serializable, Serializable>) 
								 ApplicationContextHolder.getBean("redisTemplate");
						 //判断存在key
						 if(!CacheUtil.getCache().exists(key)){
							 flag = true;
						 }		  
						 RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());  
						 //不存在设置过期时间
						 if(flag){
							 counter.expire(DataConstants.GOOD_TTL, TimeUnit.SECONDS);
						 }		  
						 counter.incrementAndGet();  
						
					}
				  });
		} finally {
			es.shutdown();
		}
		  
		          	    
	}
	
	/**
		* @Title: countAll 
	* @Description: 获取计数
	* @param @param redisTemplate
	* @param @return    设定文件 
	* @return long    返回类型 
	* @throws
	 */
	@SuppressWarnings("unchecked")
	private static String countAll(String key) {
		RedisTemplate<Serializable, Serializable> redisTemplate = (RedisTemplate<Serializable, Serializable>) ApplicationContextHolder.getBean("redisTemplate");
	    RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());  
        return String.valueOf(counter.get());
    }

本人的逻辑是只统计一天所以设置超时时间为24小时,key也加了日期区分

具体使用用法可以百度RedisAtomicLong ,本文只是浅显的使用,若有不正确地方,希望大家不吝赐教.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章