The interface uses cache to see how much cache hit rate has been improved. I'd like to make a statistical method. I'd like to use AtomicImteger on a single machine. Considering the multiple server calls in the distributed cluster, I'd like to use redis to make statistics. The original idea is very simple to use distributed lock control to operate with only one thread at a time, but I need to get data + 1 again In the three-step process of putting data into the lock, the thread that did not acquire the lock was waiting and retried to acquire the lock, but in this case, some threads would starve to death. In order to prevent the thread from starving to death and make the number of retries limit more than the number of times, giving up the statistics would make the general trend correct, and the number would be biased. The mechanism needs to be considered. One statistical method does not want to waste too much Brain cells, so pass sees that redis has RedisAtomicLong, so it's considered to use this to do it
Direct code rejection
/** * * @Title: incrementAndGet * @Description: Count +1 * @param @param redisTemplate * @param @param key Settings file * @return void Return type * @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"); //Judge the existence of key if(!CacheUtil.getCache().exists(key)){ flag = true; } RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory()); //Set expiration time does not exist if(flag){ counter.expire(DataConstants.GOOD_TTL, TimeUnit.SECONDS); } counter.incrementAndGet(); } }); } finally { es.shutdown(); } } /** * * @Title: countAll * @Description: Acquisition count * @param @param redisTemplate * @param @return Settings file * @return long Return type * @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()); }
My logic is to count only one day, so I set the timeout to 24 hours, and the key also adds date differentiation
The specific usage can be Baidu RedisAtomicLong. This article is only for simple use. If there is something wrong, I hope you can give me some advice