Java利用Redis實現(xiàn)高并發(fā)計數(shù)器的示例代碼
業(yè)務(wù)需求中經(jīng)常有需要用到計數(shù)器的場景:譬如一個手機(jī)號一天限制發(fā)送5條短信、一個接口一分鐘限制多少請求、一個接口一天限制調(diào)用多少次等等。使用Redis的Incr自增命令可以輕松實現(xiàn)以上需求。以一個接口一天限制調(diào)用次數(shù)為例:
/** * 是否拒絕服務(wù) * @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發(fā)動機(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)用接口之前,先獲得下計數(shù)器自增后的值,如果小于限制,放行,執(zhí)行后面的代碼。如果大于限制,則攔截掉。
JedisUtil工具類:
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 (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實現(xiàn)高并發(fā)計數(shù)器的示例代碼的文章就介紹到這了,更多相關(guān)Java Redis 高并發(fā)計數(shù)器內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析2. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析3. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp4. SharePoint Server 2019新特性介紹5. ASP中常用的22個FSO文件操作函數(shù)整理6. React+umi+typeScript創(chuàng)建項目的過程7. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究8. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁9. 三個不常見的 HTML5 實用新特性簡介10. php測試程序運行速度和頁面執(zhí)行速度的代碼
