業(yè)務(wù)需求中經(jīng)常有需要用到計(jì)數(shù)器的場景:譬如一個(gè)手機(jī)號(hào)一天限制發(fā)送5條短信、一個(gè)接口一分鐘限制多少請求、一個(gè)接口一天限制調(diào)用多少次等等。使用Redis的Incr自增命令可以輕松實(shí)現(xiàn)以上需求。以一個(gè)接口一天限制調(diào)用次數(shù)為例:
1
2
3
4
5
6
7
8
9
10
11
|
/** * 是否拒絕服務(wù) * @return */ private boolean denialOfService(String userId){ long count=JedisUtil.setIncr(DateUtil.getDate()+ "&" +userId+ "&" + "queryCarViolation" , 86400 ); if (count<= 10 ){ return false ; } return true ; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
/** * 查詢違章 * @param plateNumber車牌 * @param vin 車架號(hào) * @param engineNo發(fā)動(dòng)機(jī) * @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 ; } //沒超過限制,業(yè)務(wù)邏輯…… } |
每次調(diào)用接口之前,先獲得下計(jì)數(shù)器自增后的值,如果小于限制,放行,執(zhí)行后面的代碼。如果大于限制,則攔截掉。
JedisUtil工具類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
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; } /** * 對某個(gè)鍵的值自增 * @author liboyi * @param key 鍵 * @param cacheSeconds 超時(shí)時(shí)間,0為不超時(shí) * @return */ public static long setIncr(String key, int cacheSeconds) { long result = 0 ; Jedis jedis = null ; try { jedis = jedisPool.getResource(); result =jedis.incr(key); if (result<= 1 && 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; } } |
到此這篇關(guān)于Java利用Redis實(shí)現(xiàn)高并發(fā)計(jì)數(shù)器的示例代碼的文章就介紹到這了,更多相關(guān)Java Redis 高并發(fā)計(jì)數(shù)器內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/qq_33556185/article/details/79427271