本篇內(nèi)容介紹了“怎么用SpringBoot+redis實(shí)現(xiàn)重復(fù)提交”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
成都創(chuàng)新互聯(lián)公司是一家專注于成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)與策劃設(shè)計(jì),蚌埠網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)10多年,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:蚌埠等地區(qū)。蚌埠做網(wǎng)站價(jià)格咨詢:13518219792
在實(shí)際的開發(fā)項(xiàng)目中,一個(gè)對外暴露的接口往往會面臨很多次請求,我們來解釋一下冪等的概念:任意多次執(zhí)行所產(chǎn)生的影響均與一次執(zhí)行的影響相同。按照這個(gè)含義,最終的含義就是 對數(shù)據(jù)庫的影響只能是一次性的,不能重復(fù)處理。如何保證其冪等性,通常有以下手段:
數(shù)據(jù)庫建立唯一性索引,可以保證最終插入數(shù)據(jù)庫的只有一條數(shù)據(jù)
token機(jī)制,每次接口請求前先獲取一個(gè)token,然后再下次請求的時(shí)候在請求的header體中加上這個(gè)token,后臺進(jìn)行驗(yàn)證,如果驗(yàn)證通過刪除token,下次請求再次判斷token
悲觀鎖或者樂觀鎖,悲觀鎖可以保證每次for update的時(shí)候其他sql無法update數(shù)據(jù)(在數(shù)據(jù)庫引擎是innodb的時(shí)候,select的條件必須是唯一索引,防止鎖全表)
先查詢后判斷,首先通過查詢數(shù)據(jù)庫是否存在數(shù)據(jù),如果存在證明已經(jīng)請求過了,直接拒絕該請求,如果沒有存在,就證明是第一次進(jìn)來,直接放行。
redis實(shí)現(xiàn)自動(dòng)冪等的原理圖:

搭建redis的服務(wù)Api
首先是搭建redis服務(wù)器。
引入springboot中到的redis的stater,或者Spring封裝的jedis也可以,后面主要用到的api就是它的set方法和exists方法,這里我們使用springboot的封裝好的redisTemplate
/** * redis工具類 */ @Component public class RedisService { @Autowired private RedisTemplate redisTemplate; /** * 寫入緩存 * @param key * @param value * @return */ public boolean set(final String key, Object value) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 寫入緩存設(shè)置時(shí)效時(shí)間 * @param key * @param value * @return */ public boolean setEx(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 判斷緩存中是否有對應(yīng)的value * @param key * @return */ public boolean exists(final String key) { return redisTemplate.hasKey(key); } /** * 讀取緩存 * @param key * @return */ public Object get(final String key) { Object result = null; ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); result = operations.get(key); return result; } /** * 刪除對應(yīng)的value * @param key */ public boolean remove(final String key) { if (exists(key)) { Boolean delete = redisTemplate.delete(key); return delete; } return false; } }自定義注解AutoIdempotent
自定義一個(gè)注解,定義此注解的主要目的是把它添加在需要實(shí)現(xiàn)冪等的方法上,凡是某個(gè)方法注解了它,都會實(shí)現(xiàn)自動(dòng)冪等。后臺利用反射如果掃描到這個(gè)注解,就會處理這個(gè)方法實(shí)現(xiàn)自動(dòng)冪等,使用元注解ElementType.METHOD表示它只能放在方法上,etentionPolicy.RUNTIME表示它在運(yùn)行時(shí)
@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface AutoIdempotent { }token創(chuàng)建和檢驗(yàn)
token服務(wù)接口:我們新建一個(gè)接口,創(chuàng)建token服務(wù),里面主要是兩個(gè)方法,一個(gè)用來創(chuàng)建token,一個(gè)用來驗(yàn)證token。創(chuàng)建token主要產(chǎn)生的是一個(gè)字符串,檢驗(yàn)token的話主要是傳達(dá)request對象,為什么要傳request對象呢?主要作用就是獲取header里面的token,然后檢驗(yàn),通過拋出的Exception來獲取具體的報(bào)錯(cuò)信息返回給前端
public interface TokenService { /** * 創(chuàng)建token * @return */ public String createToken(); /** * 檢驗(yàn)token * @param request * @return */ public boolean checkToken(HttpServletRequest request) throws Exception; }token的服務(wù)實(shí)現(xiàn)類:token引用了redis服務(wù),創(chuàng)建token采用隨機(jī)算法工具類生成隨機(jī)uuid字符串,然后放入到redis中(為了防止數(shù)據(jù)的冗余保留,這里設(shè)置過期時(shí)間為10000秒,具體可視業(yè)務(wù)而定),如果放入成功,最后返回這個(gè)token值。checkToken方法就是從header中獲取token到值(如果header中拿不到,就從paramter中獲取),如若不存在,直接拋出異常。這個(gè)異常信息可以被攔截器捕捉到,然后返回給前端。
@Service public class TokenServiceImpl implements TokenService { @Autowired private RedisService redisService; /** * 創(chuàng)建token * * @return */ @Override public String createToken() { String str = RandomUtil.randomUUID(); StrBuilder token = new StrBuilder(); try { token.append(Constant.Redis.TOKEN_PREFIX).append(str); redisService.setEx(token.toString(), token.toString(),10000L); boolean notEmpty = StrUtil.isNotEmpty(token.toString()); if (notEmpty) { return token.toString(); } }catch (Exception ex){ ex.printStackTrace(); } return null; } /** * 檢驗(yàn)token * * @param request * @return */ @Override public boolean checkToken(HttpServletRequest request) throws Exception { String token = request.getHeader(Constant.TOKEN_NAME); if (StrUtil.isBlank(token)) {// header中不存在token token = request.getParameter(Constant.TOKEN_NAME); if (StrUtil.isBlank(token)) {// parameter中也不存在token throw new ServiceException(Constant.ResponseCode.ILLEGAL_ARGUMENT, 100); } } if (!redisService.exists(token)) { throw new ServiceException(Constant.ResponseCode.REPETITIVE_OPERATION, 200); } boolean remove = redisService.remove(token); if (!remove) { throw new ServiceException(Constant.ResponseCode.REPETITIVE_OPERATION, 200); } return true; } }攔截器的配置
web配置類,實(shí)現(xiàn)WebMvcConfigurerAdapter,主要作用就是添加autoIdempotentInterceptor到配置類中,這樣我們到攔截器才能生效,注意使用@Configuration注解,這樣在容器啟動(dòng)是時(shí)候就可以添加進(jìn)入context中
@Configuration public class WebConfiguration extends WebMvcConfigurerAdapter { @Resource private AutoIdempotentInterceptor autoIdempotentInterceptor; /** * 添加攔截器 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(autoIdempotentInterceptor); super.addInterceptors(registry); } }攔截處理器:主要的功能是攔截掃描到AutoIdempotent到注解到方法,然后調(diào)用tokenService的checkToken()方法校驗(yàn)token是否正確,如果捕捉到異常就將異常信息渲染成json返回給前端
/** * 攔截器 */ @Component public class AutoIdempotentInterceptor implements HandlerInterceptor { @Autowired private TokenService tokenService; /** * 預(yù)處理 * * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (!(handler instanceof HandlerMethod)) { return true; } HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); //被ApiIdempotment標(biāo)記的掃描 AutoIdempotent methodmethodAnnotation = method.getAnnotation(AutoIdempotent.class); if (methodAnnotation != null) { try { return tokenService.checkToken(request);// 冪等性校驗(yàn), 校驗(yàn)通過則放行, 校驗(yàn)失敗則拋出異常, 并通過統(tǒng)一異常處理返回友好提示 }catch (Exception ex){ ResultVo failedResult = ResultVo.getFailedResult(101, ex.getMessage()); writeReturnJson(response, JSONUtil.toJsonStr(failedResult)); throw ex; } } //必須返回true,否則會被攔截一切請求 return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } /** * 返回的json值 * @param response * @param json * @throws Exception */ private void writeReturnJson(HttpServletResponse response, String json) throws Exception{ PrintWriter writer = null; response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=utf-8"); try { writer = response.getWriter(); writer.print(json); } catch (IOException e) { } finally { if (writer != null) writer.close(); } } }測試用例
模擬業(yè)務(wù)請求類,首先我們需要通過/get/token路徑通過getToken()方法去獲取具體的token,然后我們調(diào)用testIdempotence方法,這個(gè)方法上面注解了@AutoIdempotent,攔截器會攔截所有的請求,當(dāng)判斷到處理的方法上面有該注解的時(shí)候,就會調(diào)用TokenService中的checkToken()方法,如果捕獲到異常會將異常拋出調(diào)用者,下面我們來模擬請求一下:
@RestController public class BusinessController { @Resource private TokenService tokenService; @Resource private TestService testService; @PostMapping("/get/token") public String getToken(){ String token = tokenService.createToken(); if (StrUtil.isNotEmpty(token)) { ResultVo resultVo = new ResultVo(); resultVo.setCode(Constant.code_success); resultVo.setMessage(Constant.SUCCESS); resultVo.setData(token); return JSONUtil.toJsonStr(resultVo); } return StrUtil.EMPTY; } @AutoIdempotent @PostMapping("/test/Idempotence") public String testIdempotence() { String businessResult = testService.testIdempotence(); if (StrUtil.isNotEmpty(businessResult)) { ResultVo successResult = ResultVo.getSuccessResult(businessResult); return JSONUtil.toJsonStr(successResult); } return StrUtil.EMPTY; } }使用postman請求,首先訪問get/token路徑獲取到具體到token:

利用獲取到到token,然后放到具體請求到header中,可以看到第一次請求成功,接著我們請求第二次:

第二次請求,返回到是重復(fù)性操作,可見重復(fù)性驗(yàn)證通過,再多次請求到時(shí)候我們只讓其第一次成功,第二次就是失敗:

“怎么用SpringBoot+Redis實(shí)現(xiàn)重復(fù)提交”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
文章題目:怎么用SpringBoot+Redis實(shí)現(xiàn)重復(fù)提交
本文URL:http://www.chinadenli.net/article12/iphgdc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供用戶體驗(yàn)、標(biāo)簽優(yōu)化、ChatGPT、自適應(yīng)網(wǎng)站、做網(wǎng)站、網(wǎng)站設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)