<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          瞬間幾千次的重復(fù)提交,我用 SpringBoot+Redis 扛住了

          共 9130字,需瀏覽 19分鐘

           ·

          2021-12-24 07:54

          點(diǎn)擊上方“碼農(nóng)突圍”,馬上關(guān)注

          這里是碼農(nóng)充電第一站,回復(fù)“666”,獲取一份專屬大禮包

          真愛,請(qǐng)?jiān)O(shè)置“星標(biāo)”或點(diǎn)個(gè)“在看

          作者 |?慕容千語(yǔ)

          來源 |?http://suo.im/5PaEZI

          在實(shí)際的開發(fā)項(xiàng)目中,一個(gè)對(duì)外暴露的接口往往會(huì)面臨,瞬間大量的重復(fù)的請(qǐng)求提交,如果想過濾掉重復(fù)請(qǐng)求造成對(duì)業(yè)務(wù)的傷害,那就需要實(shí)現(xiàn)冪等!

          我們來解釋一下冪等的概念:

          任意多次執(zhí)行所產(chǎn)生的影響均與一次執(zhí)行的影響相同。按照這個(gè)含義,最終的含義就是 對(duì)數(shù)據(jù)庫(kù)的影響只能是一次性的,不能重復(fù)處理。

          如何保證其冪等性,通常有以下手段:

          1、數(shù)據(jù)庫(kù)建立唯一性索引,可以保證最終插入數(shù)據(jù)庫(kù)的只有一條數(shù)據(jù)
          2、token機(jī)制,每次接口請(qǐng)求前先獲取一個(gè)token,然后再下次請(qǐng)求的時(shí)候在請(qǐng)求的header體中加上這個(gè)token,后臺(tái)進(jìn)行驗(yàn)證,如果驗(yàn)證通過刪除token,下次請(qǐng)求再次判斷token
          3、悲觀鎖或者樂觀鎖,悲觀鎖可以保證每次for update的時(shí)候其他sql無法update數(shù)據(jù)(在數(shù)據(jù)庫(kù)引擎是innodb的時(shí)候,select的條件必須是唯一索引,防止鎖全表)
          4、先查詢后判斷,首先通過查詢數(shù)據(jù)庫(kù)是否存在數(shù)據(jù),如果存在證明已經(jīng)請(qǐng)求過了,直接拒絕該請(qǐng)求,如果沒有存在,就證明是第一次進(jìn)來,直接放行。

          redis實(shí)現(xiàn)自動(dòng)冪等的原理圖:

          一、搭建redis的服務(wù)Api

          1、首先是搭建redis服務(wù)器。

          2、引入springboot中到的redis的stater,或者Spring封裝的jedis也可以,后面主要用到的api就是它的set方法和exists方法,這里我們使用springboot的封裝好的redisTemplate

          1. /**

          2. * redis工具類

          3. */

          4. @Component

          5. publicclassRedisService{

          6. ? ?@Autowired

          7. ? ?privateRedisTemplate redisTemplate;

          8. ? ?/**

          9. ? ? * 寫入緩存

          10. ? ? * @param key

          11. ? ? * @param value

          12. ? ? * @return

          13. ? ? */

          14. ? ?publicbooleanset(finalString key, Object value) {

          15. ? ? ? ?boolean result = false;

          16. ? ? ? ?try{

          17. ? ? ? ? ? ?ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();

          18. ? ? ? ? ? ?operations.set(key, value);

          19. ? ? ? ? ? ?result = true;

          20. ? ? ? ?} catch(Exception e) {

          21. ? ? ? ? ? ?e.printStackTrace();

          22. ? ? ? ?}

          23. ? ? ? ?return result;

          24. ? ?}

          25. ? ?/**

          26. ? ? * 寫入緩存設(shè)置時(shí)效時(shí)間

          27. ? ? * @param key

          28. ? ? * @param value

          29. ? ? * @return

          30. ? ? */

          31. ? ?publicboolean setEx(finalString key, Object value, Long expireTime) {

          32. ? ? ? ?boolean result = false;

          33. ? ? ? ?try{

          34. ? ? ? ? ? ?ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();

          35. ? ? ? ? ? ?operations.set(key, value);

          36. ? ? ? ? ? ?redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);

          37. ? ? ? ? ? ?result = true;

          38. ? ? ? ?} catch(Exception e) {

          39. ? ? ? ? ? ?e.printStackTrace();

          40. ? ? ? ?}

          41. ? ? ? ?return result;

          42. ? ?}

          43. ? ?/**

          44. ? ? * 判斷緩存中是否有對(duì)應(yīng)的value

          45. ? ? * @param key

          46. ? ? * @return

          47. ? ? */

          48. ? ?publicboolean exists(finalString key) {

          49. ? ? ? ?return redisTemplate.hasKey(key);

          50. ? ?}

          51. ? ?/**

          52. ? ? * 讀取緩存

          53. ? ? * @param key

          54. ? ? * @return

          55. ? ? */

          56. ? ?publicObjectget(finalString key) {

          57. ? ? ? ?Object result = null;

          58. ? ? ? ?ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();

          59. ? ? ? ?result = operations.get(key);

          60. ? ? ? ?return result;

          61. ? ?}

          62. ? ?/**

          63. ? ? * 刪除對(duì)應(yīng)的value

          64. ? ? * @param key

          65. ? ? */

          66. ? ?publicboolean remove(finalString key) {

          67. ? ? ? ?if(exists(key)) {

          68. ? ? ? ? ? ?Booleandelete= redisTemplate.delete(key);

          69. ? ? ? ? ? ?returndelete;

          70. ? ? ? ?}

          71. ? ? ? ?returnfalse;

          72. ? ?}

          73. }

          二、自定義注解AutoIdempotent

          自定義一個(gè)注解,定義此注解的主要目的是把它添加在需要實(shí)現(xiàn)冪等的方法上,凡是某個(gè)方法注解了它,都會(huì)實(shí)現(xiàn)自動(dòng)冪等。后臺(tái)利用反射如果掃描到這個(gè)注解,就會(huì)處理這個(gè)方法實(shí)現(xiàn)自動(dòng)冪等,使用元注解ElementType.METHOD表示它只能放在方法上,etentionPolicy.RUNTIME表示它在運(yùn)行時(shí)。

          1. @Target({ElementType.METHOD})

          2. @Retention(RetentionPolicy.RUNTIME)

          3. public@interfaceAutoIdempotent{

          4. }

          三、token創(chuàng)建和檢驗(yàn)

          1、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對(duì)象,為什么要傳request對(duì)象呢?主要作用就是獲取header里面的token,然后檢驗(yàn),通過拋出的Exception來獲取具體的報(bào)錯(cuò)信息返回給前端。

          1. publicinterfaceTokenService{

          2. ? ?/**

          3. ? ? * 創(chuàng)建token

          4. ? ? * @return

          5. ? ? */

          6. ? ?public ?String createToken();

          7. ? ?/**

          8. ? ? * 檢驗(yàn)token

          9. ? ? * @param request

          10. ? ? * @return

          11. ? ? */

          12. ? ?publicboolean checkToken(HttpServletRequest request) throwsException;

          13. }

          2、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è)異常信息可以被攔截器捕捉到,然后返回給前端。

          1. @Service

          2. publicclassTokenServiceImplimplementsTokenService{

          3. ? ?@Autowired

          4. ? ?privateRedisService redisService;

          5. ? ?/**

          6. ? ? * 創(chuàng)建token

          7. ? ? *

          8. ? ? * @return

          9. ? ? */

          10. ? ?@Override

          11. ? ?publicString createToken() {

          12. ? ? ? ?String str = RandomUtil.randomUUID();

          13. ? ? ? ?StrBuilder token = newStrBuilder();

          14. ? ? ? ?try{

          15. ? ? ? ? ? ?token.append(Constant.Redis.TOKEN_PREFIX).append(str);

          16. ? ? ? ? ? ?redisService.setEx(token.toString(), token.toString(),10000L);

          17. ? ? ? ? ? ?boolean notEmpty = StrUtil.isNotEmpty(token.toString());

          18. ? ? ? ? ? ?if(notEmpty) {

          19. ? ? ? ? ? ? ? ?return token.toString();

          20. ? ? ? ? ? ?}

          21. ? ? ? ?}catch(Exception ex){

          22. ? ? ? ? ? ?ex.printStackTrace();

          23. ? ? ? ?}

          24. ? ? ? ?returnnull;

          25. ? ?}

          26. ? ?/**

          27. ? ? * 檢驗(yàn)token

          28. ? ? *

          29. ? ? * @param request

          30. ? ? * @return

          31. ? ? */

          32. ? ?@Override

          33. ? ?publicboolean checkToken(HttpServletRequest request) throwsException{

          34. ? ? ? ?String token = request.getHeader(Constant.TOKEN_NAME);

          35. ? ? ? ?if(StrUtil.isBlank(token)) {// header中不存在token

          36. ? ? ? ? ? ?token = request.getParameter(Constant.TOKEN_NAME);

          37. ? ? ? ? ? ?if(StrUtil.isBlank(token)) {// parameter中也不存在token

          38. ? ? ? ? ? ? ? ?thrownewServiceException(Constant.ResponseCode.ILLEGAL_ARGUMENT, 100);

          39. ? ? ? ? ? ?}

          40. ? ? ? ?}

          41. ? ? ? ?if(!redisService.exists(token)) {

          42. ? ? ? ? ? ?thrownewServiceException(Constant.ResponseCode.REPETITIVE_OPERATION, 200);

          43. ? ? ? ?}

          44. ? ? ? ?boolean remove = redisService.remove(token);

          45. ? ? ? ?if(!remove) {

          46. ? ? ? ? ? ?thrownewServiceException(Constant.ResponseCode.REPETITIVE_OPERATION, 200);

          47. ? ? ? ?}

          48. ? ? ? ?returntrue;

          49. ? ?}

          50. }

          四、攔截器的配置

          1、web配置類,實(shí)現(xiàn)WebMvcConfigurerAdapter,主要作用就是添加autoIdempotentInterceptor到配置類中,這樣我們到攔截器才能生效,注意使用@Configuration注解,這樣在容器啟動(dòng)是時(shí)候就可以添加進(jìn)入context中。

          1. @Configuration

          2. publicclassWebConfigurationextendsWebMvcConfigurerAdapter{

          3. ? ?@Resource

          4. ? privateAutoIdempotentInterceptor autoIdempotentInterceptor;

          5. ? ?/**

          6. ? ? * 添加攔截器

          7. ? ? * @param registry

          8. ? ? */

          9. ? ?@Override

          10. ? ?publicvoid addInterceptors(InterceptorRegistry registry) {

          11. ? ? ? ?registry.addInterceptor(autoIdempotentInterceptor);

          12. ? ? ? ?super.addInterceptors(registry);

          13. ? ?}

          14. }

          2、攔截處理器:主要的功能是攔截掃描到AutoIdempotent到注解到方法,然后調(diào)用tokenService的checkToken()方法校驗(yàn)token是否正確,如果捕捉到異常就將異常信息渲染成json返回給前端

          1. /**

          2. * 攔截器

          3. */

          4. @Component

          5. publicclassAutoIdempotentInterceptorimplementsHandlerInterceptor{

          6. ? ?@Autowired

          7. ? ?privateTokenService tokenService;

          8. ? ?/**

          9. ? ? * 預(yù)處理

          10. ? ? *

          11. ? ? * @param request

          12. ? ? * @param response

          13. ? ? * @param handler

          14. ? ? * @return

          15. ? ? * @throws Exception

          16. ? ? */

          17. ? ?@Override

          18. ? ?publicboolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throwsException{

          19. ? ? ? ?if(!(handler instanceofHandlerMethod)) {

          20. ? ? ? ? ? ?returntrue;

          21. ? ? ? ?}

          22. ? ? ? ?HandlerMethod handlerMethod = (HandlerMethod) handler;

          23. ? ? ? ?Method method = handlerMethod.getMethod();

          24. ? ? ? ?//被ApiIdempotment標(biāo)記的掃描

          25. ? ? ? ?AutoIdempotent methodAnnotation = method.getAnnotation(AutoIdempotent.class);

          26. ? ? ? ?if(methodAnnotation != null) {

          27. ? ? ? ? ? ?try{

          28. ? ? ? ? ? ? ? ?return tokenService.checkToken(request);// 冪等性校驗(yàn), 校驗(yàn)通過則放行, 校驗(yàn)失敗則拋出異常, 并通過統(tǒng)一異常處理返回友好提示

          29. ? ? ? ? ? ?}catch(Exception ex){

          30. ? ? ? ? ? ? ? ?ResultVo failedResult = ResultVo.getFailedResult(101, ex.getMessage());

          31. ? ? ? ? ? ? ? ?writeReturnJson(response, JSONUtil.toJsonStr(failedResult));

          32. ? ? ? ? ? ? ? ?throw ex;

          33. ? ? ? ? ? ?}

          34. ? ? ? ?}

          35. ? ? ? ?//必須返回true,否則會(huì)被攔截一切請(qǐng)求

          36. ? ? ? ?returntrue;

          37. ? ?}

          38. ? ?@Override

          39. ? ?publicvoid postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throwsException{

          40. ? ?}

          41. ? ?@Override

          42. ? ?publicvoid afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throwsException{

          43. ? ?}

          44. ? ?/**

          45. ? ? * 返回的json值

          46. ? ? * @param response

          47. ? ? * @param json

          48. ? ? * @throws Exception

          49. ? ? */

          50. ? ?privatevoid writeReturnJson(HttpServletResponse response, String json) throwsException{

          51. ? ? ? ?PrintWriter writer = null;

          52. ? ? ? ?response.setCharacterEncoding("UTF-8");

          53. ? ? ? ?response.setContentType("text/html; charset=utf-8");

          54. ? ? ? ?try{

          55. ? ? ? ? ? ?writer = response.getWriter();

          56. ? ? ? ? ? ?writer.print(json);

          57. ? ? ? ?} catch(IOException e) {

          58. ? ? ? ?} finally{

          59. ? ? ? ? ? ?if(writer != null)

          60. ? ? ? ? ? ? ? ?writer.close();

          61. ? ? ? ?}

          62. ? ?}

          63. }

          五、測(cè)試用例

          1、模擬業(yè)務(wù)請(qǐng)求類

          首先我們需要通過/get/token路徑通過getToken()方法去獲取具體的token,然后我們調(diào)用testIdempotence方法,這個(gè)方法上面注解了@AutoIdempotent,攔截器會(huì)攔截所有的請(qǐng)求,當(dāng)判斷到處理的方法上面有該注解的時(shí)候,就會(huì)調(diào)用TokenService中的checkToken()方法,如果捕獲到異常會(huì)將異常拋出調(diào)用者,下面我們來模擬請(qǐng)求一下:

          1. @RestController

          2. publicclassBusinessController{

          3. ? ?@Resource

          4. ? ?privateTokenService tokenService;

          5. ? ?@Resource

          6. ? ?privateTestService testService;

          7. ? ?@PostMapping("/get/token")

          8. ? ?publicString ?getToken(){

          9. ? ? ? ?String token = tokenService.createToken();

          10. ? ? ? ?if(StrUtil.isNotEmpty(token)) {

          11. ? ? ? ? ? ?ResultVo resultVo = newResultVo();

          12. ? ? ? ? ? ?resultVo.setCode(Constant.code_success);

          13. ? ? ? ? ? ?resultVo.setMessage(Constant.SUCCESS);

          14. ? ? ? ? ? ?resultVo.setData(token);

          15. ? ? ? ? ? ?returnJSONUtil.toJsonStr(resultVo);

          16. ? ? ? ?}

          17. ? ? ? ?returnStrUtil.EMPTY;

          18. ? ?}

          19. ? ?@AutoIdempotent

          20. ? ?@PostMapping("/test/Idempotence")

          21. ? ?publicString testIdempotence() {

          22. ? ? ? ?String businessResult = testService.testIdempotence();

          23. ? ? ? ?if(StrUtil.isNotEmpty(businessResult)) {

          24. ? ? ? ? ? ?ResultVo successResult = ResultVo.getSuccessResult(businessResult);

          25. ? ? ? ? ? ?returnJSONUtil.toJsonStr(successResult);

          26. ? ? ? ?}

          27. ? ? ? ?returnStrUtil.EMPTY;

          28. ? ?}

          29. }

          2、使用postman請(qǐng)求

          首先訪問get/token路徑獲取到具體到token:

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

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

          六、總結(jié)

          本篇博客介紹了使用springboot和攔截器、redis來優(yōu)雅的實(shí)現(xiàn)接口冪等,對(duì)于冪等在實(shí)際的開發(fā)過程中是十分重要的,因?yàn)橐粋€(gè)接口可能會(huì)被無數(shù)的客戶端調(diào)用,如何保證其不影響后臺(tái)的業(yè)務(wù)處理,如何保證其只影響數(shù)據(jù)一次是非常重要的,它可以防止產(chǎn)生臟數(shù)據(jù)或者亂數(shù)據(jù),也可以減少并發(fā)量,實(shí)乃十分有益的一件事。而傳統(tǒng)的做法是每次判斷數(shù)據(jù),這種做法不夠智能化和自動(dòng)化,比較麻煩。而今天的這種自動(dòng)化處理也可以提升程序的伸縮性。

          -End-

          最近有一些小伙伴,讓我?guī)兔φ乙恍?面試題?資料,于是我翻遍了收藏的 5T 資料后,匯總整理出來,可以說是程序員面試必備!所有資料都整理到網(wǎng)盤了,歡迎下載!

          點(diǎn)擊??卡片,關(guān)注后回復(fù)【面試題】即可獲取

          瀏覽 43
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  99精品视频国产 | 美女吊嘿网站 | 色老板免费精品无码免费视频 | 俺来也俺去也www色官 | 天天日天天搞天天爽 |