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

 

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

直接甩代码缓存

/**
    * 
	* @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 ,本文只是浅显的使用,如有不正确地方,但愿你们不吝赐教.分布式

相关文章
相关标签/搜索