Home  >  Article  >  Database  >  redis implements high concurrency counting

redis implements high concurrency counting

尚
forward
2020-04-27 09:12:132533browse

redis implements high concurrency counting

There are often scenarios where counters are needed in business requirements: for example, a mobile phone number is limited to sending 5 text messages a day, an interface is limited to how many requests per minute, and an interface is limited to how many calls a day. etc. The above requirements can be easily achieved using Redis's Incr auto-increment command. Take the limit of the number of calls to an interface in a day as an example:

	/**
	 * 是否拒绝服务
	 * @return
	 */
	private boolean denialOfService(String userId){
		long count=JedisUtil.setIncr(DateUtil.getDate()+"&"+userId+"&"+"queryCarViolation", 86400);
		if(count<=10){
			return false;
		}
		return true;
	}
       /**
	 * 查询违章
	 * @param plateNumber车牌
	 * @param vin 车架号
	 * @param engineNo发动机
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryCarViolationList.json")
	@AuthorizationApi
	public void queryCarViolationList(@CurrentToken Token token,String plateNumber,String vin,
        String engineNo,HttpServletRequest request,HttpServletResponse response) throws Exception {
	    String userId=token.getUserId();
            //超过限制,拦截请求
      if(denialOfService(userId)){
		  apiData(request, response, ReqJson.error(CarError.ONLY_5_TIMES_A_DAY_CAN_BE_FOUND));
		  return;
	    }
		//没超过限制,业务逻辑……
 }

Before each call to the interface, first obtain the value after the counter has been incremented. If it is less than the limit, let it go and execute the following code. If it is greater than the limit, it will be intercepted.

JedisUtil tool class:

public class JedisUtil {
	protected final static Logger logger = Logger.getLogger(JedisUtil.class);
	private static  JedisPool jedisPool;
	
	@Autowired(required = true)
	public void setJedisPool(JedisPool jedisPool) {
		JedisUtil.jedisPool = jedisPool;
	}
	/**
	 * 对某个键的值自增
	 * @author liboyi
	 * @param key 键
	 * @param cacheSeconds 超时时间,0为不超时
	 * @return
	 */
	public static long setIncr(String key, int cacheSeconds) {
		long result = 0;
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			result =jedis.incr(key);
			if (cacheSeconds != 0) {
			 jedis.expire(key, cacheSeconds);
			}
			logger.debug("set "+ key + " = " + result);
		} catch (Exception e) {
			logger.warn("set "+ key + " = " + result);
		} finally {
			jedisPool.returnResource(jedis);
		}
		return result;
	}
}	

For more redis knowledge, please pay attention to the redis introductory tutorial column.

The above is the detailed content of redis implements high concurrency counting. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete