There are often scenarios where counters need to be used in business requirements: for example, a mobile number restricts the sending of 5 messages a day, how many requests an interface can limit in one minute, how many times a single interface is limited to one day, and so on. The above requirements can be easily achieved by using the Redis incr command. Take an interface one day to limit the number of calls as an example:
/**
* Deny service
* @return *
*
Private Boolean denialofservice (String userId) {
long count= JEDISUTIL.SETINCR (Dateutil.getdate () + "&" +userid+ "&" + "Querycarviolation", 86400);
if (count<=10) {return
false;
}
return true;
}
/** *
@param platenumber license plate *
@param vin frame number
* @param engineno engine
* @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 ();
Over limit, intercept request
if (Denialofservice (userId)) {
Apidata (request, Response, Reqjson.error (carerror.only_5_ Times_a_day_can_be_found));
return;
}
No more than limits, business logic ...
}
Each time the interface is invoked, get the value of the next counter, if less than the limit, release, execute the following code. If it is greater than the limit, it is blocked.
Jedisutil Tool Class:
public class Jedisutil {protected final static Logger = Logger (Logger.getlogger);
private static Jedispool Jedispool;
@Autowired (required = true) public void Setjedispool (Jedispool jedispool) {jedisutil.jedispool = Jedispool; /** * The value of a key is self-@author liboyi * @param key * @param cacheseconds timeout, 0 is not timeout * @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; }
}