SpringBoot+Redis實現接口冪等性

1.簡介

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

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

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

2.實現過程

  • 引入meavn依賴

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
    
  • spring配置文件寫入

    server.port=8080
    core.datasource.druid.enabled=true
    core.datasource.druid.url=jdbc:mysql://192.168.1.225:3306/?useUnicode=true&characterEncoding=UTF-8
    core.datasource.druid.username=root
    core.datasource.druid.password=
    core.redis.enabled=true
    spring.redis.host=192.168.1.225 #本機的redis地址
    spring.redis.port=16379
    spring.redis.database=3
    spring.redis.jedis.pool.max-active=10
    spring.redis.jedis.pool.max-idle=10
    spring.redis.jedis.pool.max-wait=5s
    spring.redis.jedis.pool.min-idle=10
    
  • 引入springboot中到的redis的stater,或者Spring封裝的jedis也可以,後面主要用到的api就是它的set方法和exists方法,這裏我們使用springboot的封裝好的redisTemplate

    package cn.smallmartial.demo.utils;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.ValueOperations;
    import org.springframework.stereotype.Component;
    
    import java.io.Serializable;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;
    
    /**
     * @Author smallmartial
     * @Date 2020/4/16
     * @Email [email protected]
     */
    @Component
    public class RedisUtil {
    
        @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;
        }
    
        /**
         * 寫入緩存設置時間
         *
         * @param key
         * @param value
         * @param expireTime
         * @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;
        }
    
        /**
         * 讀取緩存
         *
         * @param key
         * @return
         */
        public Object get(final String key) {
            Object result = null;
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            result = operations.get(key);
            return result;
        }
    
        /**
         * 刪除對應的value
         *
         * @param key
         */
        public boolean remove(final String key) {
            if (exists(key)) {
                Boolean delete = redisTemplate.delete(key);
                return delete;
            }
            return false;
    
        }
    
        /**
         * 判斷key是否存在
         *
         * @param key
         * @return
         */
        public boolean exists(final String key) {
            boolean result = false;
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            if (Objects.nonNull(operations.get(key))) {
                result = true;
            }
            return result;
        }
    
    
    }
    
    
  • 自定義註解AutoIdempotent

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

    @Target({ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface AutoIdempotent {
      
    }
    
  • toKen的創建和實現

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

    public interface TokenService {
    
        /**
         * 創建token
         * @return
         */
        public  String createToken();
    
        /**
         * 檢驗token
         * @param request
         * @return
         */
        public boolean checkToken(HttpServletRequest request) throws Exception;
    
    }
    

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

    package cn.smallmartial.demo.service.impl;
    
    import cn.smallmartial.demo.bean.RedisKeyPrefix;
    import cn.smallmartial.demo.bean.ResponseCode;
    import cn.smallmartial.demo.exception.ApiResult;
    import cn.smallmartial.demo.exception.BusinessException;
    import cn.smallmartial.demo.service.TokenService;
    import cn.smallmartial.demo.utils.RedisUtil;
    import io.netty.util.internal.StringUtil;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.util.StringUtils;
    
    import javax.servlet.http.HttpServletRequest;
    import java.util.Random;
    import java.util.UUID;
    
    /**
     * @Author smallmartial
     * @Date 2020/4/16
     * @Email [email protected]
     */
    @Service
    public class TokenServiceImpl implements TokenService {
        @Autowired
        private RedisUtil redisService;
    
        /**
         * 創建token
         *
         * @return
         */
        @Override
        public String createToken() {
            String str = UUID.randomUUID().toString().replace("-", "");
            StringBuilder token = new StringBuilder();
            try {
                token.append(RedisKeyPrefix.TOKEN_PREFIX).append(str);
                redisService.setEx(token.toString(), token.toString(), 10000L);
                boolean empty = StringUtils.isEmpty(token.toString());
                if (!empty) {
                    return token.toString();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }
    
        /**
         * 檢驗token
         *
         * @param request
         * @return
         */
        @Override
        public boolean checkToken(HttpServletRequest request) throws Exception {
    
            String token = request.getHeader(RedisKeyPrefix.TOKEN_NAME);
            if (StringUtils.isEmpty(token)) {// header中不存在token
                token = request.getParameter(RedisKeyPrefix.TOKEN_NAME);
                if (StringUtils.isEmpty(token)) {// parameter中也不存在token
                    throw new BusinessException(ApiResult.BADARGUMENT);
                }
            }
    
            if (!redisService.exists(token)) {
                throw new BusinessException(ApiResult.REPETITIVE_OPERATION);
            }
    
            boolean remove = redisService.remove(token);
            if (!remove) {
                throw new BusinessException(ApiResult.REPETITIVE_OPERATION);
            }
            return true;
        }
    }
    
    
  • 攔截器的配置

    @Configuration
    public class WebMvcConfiguration extends WebMvcConfigurationSupport {
    
        @Bean
        public AuthInterceptor authInterceptor() {
            return new AuthInterceptor();
        }
    
        /**
         * 攔截器配置
         *
         * @param registry
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(authInterceptor());
    //                .addPathPatterns("/ksb/**")
    //                .excludePathPatterns("/ksb/auth/**", "/api/common/**", "/error", "/api/*");
            super.addInterceptors(registry);
        }
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/**").addResourceLocations(
                    "classpath:/static/");
            registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                    "classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**").addResourceLocations(
                    "classpath:/META-INF/resources/webjars/");
            super.addResourceHandlers(registry);
        }
    
    
    }
    
    
  • 攔截處理器:主要的功能是攔截掃描到AutoIdempotent到註解到方法,然後調用tokenService的checkToken()方法校驗token是否正確,如果捕捉到異常就將異常信息渲染成json返回給前端

    @Slf4j
    public class AuthInterceptor extends HandlerInterceptorAdapter {
    
        @Autowired
        private TokenService tokenService;
    
        @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標記的掃描
            AutoIdempotent methodAnnotation = method.getAnnotation(AutoIdempotent.class);
            if (methodAnnotation != null) {
                try {
                    return tokenService.checkToken(request);// 冪等性校驗, 校驗通過則放行, 校驗失敗則拋出異常, 並通過統一異常處理返回友好提示
                } catch (Exception ex) {
                    throw new BusinessException(ApiResult.REPETITIVE_OPERATION);
                }
            }
            return true;
        }
    
    }
    
  • 測試用例

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

/**
 * @Author smallmartial
 * @Date 2020/4/16
 * @Email [email protected]
 */
@RestController
public class BusinessController {


    @Autowired
    private TokenService tokenService;

    @GetMapping("/get/token")
    public Object  getToken(){
        String token = tokenService.createToken();
        return ResponseUtil.ok(token) ;
    }


    @AutoIdempotent
    @GetMapping("/test/Idempotence")
    public Object testIdempotence() {
        String token = "接口冪等性測試";
        return ResponseUtil.ok(token) ;
    }
}

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

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


​ 第二次請求,返回到是重複性操作,可見重複性驗證通過,再多次請求到時候我們只讓其第一次成功,第二次就是失敗:

3.總結

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

源碼地址:https://github.com/smallmartial/springbootdemo/tree/master/springbootredis

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章