<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>

          Spring Boot + Redis 解決重復提交問題,還有誰不會??

          共 9191字,需瀏覽 19分鐘

           ·

          2021-12-17 23:19

          作者|慕容千語
          來源:www.jianshu.com/p/c806003a8…

          前言

          在實際的開發(fā)項目中,一個對外暴露的接口往往會面臨很多次請求,我們來解釋一下冪等的概念:任意多次執(zhí)行所產生的影響均與一次執(zhí)行的影響相同。按照這個含義,最終的含義就是 對數據庫的影響只能是一次性的,不能重復處理。如何保證其冪等性,通常有以下手段:

          1、數據庫建立唯一性索引,可以保證最終插入數據庫的只有一條數據。

          2、token機制,每次接口請求前先獲取一個token,然后再下次請求的時候在請求的header體中加上這個token,后臺進行驗證,如果驗證通過刪除token,下次請求再次判斷token。

          3、悲觀鎖或者樂觀鎖,悲觀鎖可以保證每次for update的時候其他sql無法update數據(在數據庫引擎是innodb的時候,select的條件必須是唯一索引,防止鎖全表)

          4、先查詢后判斷,首先通過查詢數據庫是否存在數據,如果存在證明已經請求過了,直接拒絕該請求,如果沒有存在,就證明是第一次進來,直接放行。

          redis 實現自動冪等的原理圖:

          搭建 Redis 服務 API

          1、首先是搭建redis服務器。

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

          推薦一個 Spring Boot 基礎教程及實戰(zhàn)示例:github.com/javastacks/…

          /**
          * redis工具類
          */
          @Component
          public class RedisService {

          @Autowired
          private RedisTemplate redisTemplate;

          /**
          * 寫入緩存
          * @param key
          * @param value
          * @return
          */
          public boolean set(finalString key, Object value) {
          boolean result = false;
          try {
          ValueOperations operations = redisTemplate.opsForValue();
          operations.set(key, value);
          result = true;
          } catch (Exception e) {
          e.printStackTrace();
          }
          return result;
          }

          /**
          * 寫入緩存設置時效時間
          * @param key
          * @param value
          * @return
          */
          public boolean setEx(finalString key, Object value, Long expireTime) {
          boolean result = false;
          try {
          ValueOperations operations = redisTemplate.opsForValue();
          operations.set(key, value);
          redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
          result = true;
          } catch (Exception e) {
          e.printStackTrace();
          }
          return result;
          }

          /**
          * 判斷緩存中是否有對應的value
          * @param key
          * @return
          */
          public boolean exists(finalString key) {
          return redisTemplate.hasKey(key);
          }

          /**
          * 讀取緩存
          * @param key
          * @return
          */
          public Objectget(finalString key) {
          Object result = null;
          ValueOperations operations = redisTemplate.opsForValue();
          result = operations.get(key);
          return result;
          }

          /**
          * 刪除對應的value
          * @param key
          */
          public boolean remove(finalString key) {
          if (exists(key)) {
          Boolean delete = redisTemplate.delete(key);
          return delete;
          }
          returnfalse;

          }

          }
          復制代碼

          自定義注解 AutoIdempotent

          自定義一個注解,定義此注解的主要目的是把它添加在需要實現冪等的方法上,凡是某個方法注解了它,都會實現自動冪等。后臺利用反射如果掃描到這個注解,就會處理這個方法實現自動冪等,使用元注解ElementType.METHOD表示它只能放在方法上,etentionPolicy.RUNTIME表示它在運行時。

          @Target({ElementType.METHOD})
          @Retention(RetentionPolicy.RUNTIME)
          public @interface AutoIdempotent {

          }
          復制代碼

          token 創(chuàng)建和檢驗

          token服務接口:我們新建一個接口,創(chuàng)建token服務,里面主要是兩個方法,一個用來創(chuàng)建token,一個用來驗證token。創(chuàng)建token主要產生的是一個字符串,檢驗token的話主要是傳達request對象,為什么要傳request對象呢?主要作用就是獲取header里面的token,然后檢驗,通過拋出的Exception來獲取具體的報錯信息返回給前端。

          publicinterface TokenService {

          /**
          * 創(chuàng)建token
          * @return
          */
          public String createToken();

          /**
          * 檢驗token
          * @param request
          * @return
          */
          public boolean checkToken(HttpServletRequest request) throws Exception;

          }
          復制代碼

          token的服務實現類:token引用了redis服務,創(chuàng)建token采用隨機算法工具類生成隨機uuid字符串,然后放入到redis中(為了防止數據的冗余保留,這里設置過期時間為10000秒,具體可視業(yè)務而定),如果放入成功,最后返回這個token值。checkToken方法就是從header中獲取token到值(如果header中拿不到,就從paramter中獲取),如若不存在,直接拋出異常。這個異常信息可以被攔截器捕捉到,然后返回給前端。

          @Service
          publicclass 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();
          }
          returnnull;
          }

          /**
          * 檢驗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
          thrownew ServiceException(Constant.ResponseCode.ILLEGAL_ARGUMENT, 100);
          }
          }

          if (!redisService.exists(token)) {
          thrownew ServiceException(Constant.ResponseCode.REPETITIVE_OPERATION, 200);
          }

          boolean remove = redisService.remove(token);
          if (!remove) {
          thrownew ServiceException(Constant.ResponseCode.REPETITIVE_OPERATION, 200);
          }
          returntrue;
          }
          }
          復制代碼

          攔截器的配置

          web配置類,實現WebMvcConfigurerAdapter,主要作用就是添加autoIdempotentInterceptor到配置類中,這樣我們到攔截器才能生效,注意使用@Configuration注解,這樣在容器啟動是時候就可以添加進入context中。

          @Configuration
          publicclass WebConfiguration extends WebMvcConfigurerAdapter {

          @Resource
          private AutoIdempotentInterceptor autoIdempotentInterceptor;

          /**
          * 添加攔截器
          * @param registry
          */
          @Override
          public void addInterceptors(InterceptorRegistry registry) {
          registry.addInterceptor(autoIdempotentInterceptor);
          super.addInterceptors(registry);
          }
          }
          復制代碼

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

          /**
          * 攔截器
          */
          @Component
          publicclass AutoIdempotentInterceptor implements HandlerInterceptor {

          @Autowired
          private TokenService tokenService;

          /**
          * 預處理
          *
          * @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)) {
          returntrue;
          }
          HandlerMethod handlerMethod = (HandlerMethod) handler;
          Method method = handlerMethod.getMethod();
          //被ApiIdempotment標記的掃描
          AutoIdempotent methodAnnotation = method.getAnnotation(AutoIdempotent.class);
          if (methodAnnotation != null) {
          try {
          return tokenService.checkToken(request);// 冪等性校驗, 校驗通過則放行, 校驗失敗則拋出異常, 并通過統(tǒng)一異常處理返回友好提示
          }catch (Exception ex){
          ResultVo failedResult = ResultVo.getFailedResult(101, ex.getMessage());
          writeReturnJson(response, JSONUtil.toJsonStr(failedResult));
          throw ex;
          }
          }
          //必須返回true,否則會被攔截一切請求
          returntrue;
          }

          @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è)務請求類,首先我們需要通過/get/token路徑通過getToken()方法去獲取具體的token,然后我們調用testIdempotence方法,這個方法上面注解了@AutoIdempotent,攔截器會攔截所有的請求,當判斷到處理的方法上面有該注解的時候,就會調用TokenService中的checkToken()方法,如果捕獲到異常會將異常拋出調用者,下面我們來模擬請求一下:

          @RestController
          publicclass 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中,可以看到第一次請求成功,接著我們請求第二次:

          第二次請求,返回到是重復性操作,可見重復性驗證通過,再多次請求到時候我們只讓其第一次成功,第二次就是失?。?/p>

          總結

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


          作者:Java技術棧
          鏈接:https://juejin.cn/post/7039856436762902565
          來源:稀土掘金
          著作權歸作者所有。商業(yè)轉載請聯系作者獲得授權,非商業(yè)轉載請注明出處。



          瀏覽 106
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <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>
                  91射在线观看 | 熟老女人色 | 青草福利在线视频 | 在线小黄片 | 北条麻妃在线观看免费91 |