免费在线a视频-免费在线观看a视频-免费在线观看大片影视大全-免费在线观看的视频-色播丁香-色播基地

Springboot + redis + 注解 + 攔截器來實現(xiàn)接口冪等性校驗

:2020年01月26日 wangzaiplus 腳本之家
分享到:

一、概念冪等性, 通俗的說就是一個接口, 多次發(fā)起同一個請求, 必須保證操作只能執(zhí)行一次比如:訂單接口, 不能多次創(chuàng)建訂單支付接口, 重復(fù)支付同一筆訂單只能扣一次錢支付寶回調(diào)接口, 可能會多次回調(diào), 必須...

一、概念

冪等性, 通俗的說就是一個接口, 多次發(fā)起同一個請求, 必須保證操作只能執(zhí)行一次

比如:

  • 訂單接口, 不能多次創(chuàng)建訂單

  • 支付接口, 重復(fù)支付同一筆訂單只能扣一次錢

  • 支付寶回調(diào)接口, 可能會多次回調(diào), 必須處理重復(fù)回調(diào)

  • 普通表單提交接口, 因為網(wǎng)絡(luò)超時等原因多次點擊提交, 只能成功一次

  • 等等

二、常見解決方案

  • 唯一索引 -- 防止新增臟數(shù)據(jù)

  • token機制 -- 防止頁面重復(fù)提交

  • 悲觀鎖 -- 獲取數(shù)據(jù)的時候加鎖(鎖表或鎖行)

  • 樂觀鎖 -- 基于版本號version實現(xiàn), 在更新數(shù)據(jù)那一刻校驗數(shù)據(jù)

  • 分布式鎖 -- redis(jedis、redisson)或zookeeper實現(xiàn)

  • 狀態(tài)機 -- 狀態(tài)變更, 更新數(shù)據(jù)時判斷狀態(tài)

三、本文實現(xiàn)

本文采用第2種方式實現(xiàn), 即通過redis + token機制實現(xiàn)接口冪等性校驗

四、實現(xiàn)思路

為需要保證冪等性的每一次請求創(chuàng)建一個唯一標(biāo)識token, 先獲取token, 并將此token存入redis, 請求接口時, 將此token放到header或者作為請求參數(shù)請求接口, 后端接口判斷redis中是否存在此token:

  • 如果存在, 正常處理業(yè)務(wù)邏輯, 并從redis中刪除此token, 那么, 如果是重復(fù)請求, 由于token已被刪除, 則不能通過校驗, 返回請勿重復(fù)操作提示

  • 如果不存在, 說明參數(shù)不合法或者是重復(fù)請求, 返回提示即可

五、項目簡介

  • springboot

  • redis

  • @ApiIdempotent注解 + 攔截器對請求進行攔截

  • @ControllerAdvice全局異常處理

  • 壓測工具: jmeter

說明:

本文重點介紹冪等性核心實現(xiàn), 關(guān)于springboot如何集成redis、ServerResponse、ResponseCode等細枝末節(jié)不在本文討論范圍之內(nèi), 有興趣的小伙伴可以查看我的Github項目:

https://github.com/wangzaiplus/springboot/tree/wxw

六、代碼實現(xiàn)

pom

        <!-- Redis-Jedis -->

        <dependency>

            <groupId>redis.clients</groupId>

            <artifactId>jedis</artifactId>

            <version>2.9.0</version>

        </dependency>

        <!--lombok 本文用到@Slf4j注解, 也可不引用, 自定義log即可-->

        <dependency>

            <groupId>org.projectlombok</groupId>

            <artifactId>lombok</artifactId>

            <version>1.16.10</version>

        </dependency>

JedisUtil

package com.wangzaiplus.test.util;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

@Component

@Slf4j

public class JedisUtil {

    @Autowired

    private JedisPool jedisPool;

    private Jedis getJedis() {

        return jedisPool.getResource();

    }

    /**

     * 設(shè)值

     *

     * @param key

     * @param value

     * @return

     */

    public String set(String key, String value) {

        Jedis jedis = null;

        try {

            jedis = getJedis();

            return jedis.set(key, value);

        } catch (Exception e) {

            log.error("set key:{} value:{} error", key, value, e);

            return null;

        } finally {

            close(jedis);

        }

    }

    /**

     * 設(shè)值

     *

     * @param key

     * @param value

     * @param expireTime 過期時間, 單位: s

     * @return

     */

    public String set(String key, String value, int expireTime) {

        Jedis jedis = null;

        try {

            jedis = getJedis();

            return jedis.setex(key, expireTime, value);

        } catch (Exception e) {

            log.error("set key:{} value:{} expireTime:{} error", key, value, expireTime, e);

            return null;

        } finally {

            close(jedis);

        }

    }

    /**

     * 取值

     *

     * @param key

     * @return

     */

    public String get(String key) {

        Jedis jedis = null;

        try {

            jedis = getJedis();

            return jedis.get(key);

        } catch (Exception e) {

            log.error("get key:{} error", key, e);

            return null;

        } finally {

            close(jedis);

        }

    }

    /**

     * 刪除key

     *

     * @param key

     * @return

     */

    public Long del(String key) {

        Jedis jedis = null;

        try {

            jedis = getJedis();

            return jedis.del(key.getBytes());

        } catch (Exception e) {

            log.error("del key:{} error", key, e);

            return null;

        } finally {

            close(jedis);

        }

    }

    /**

     * 判斷key是否存在

     *

     * @param key

     * @return

     */

    public Boolean exists(String key) {

        Jedis jedis = null;

        try {

            jedis = getJedis();

            return jedis.exists(key.getBytes());

        } catch (Exception e) {

            log.error("exists key:{} error", key, e);

            return null;

        } finally {

            close(jedis);

        }

    }

    /**

     * 設(shè)值key過期時間

     *

     * @param key

     * @param expireTime 過期時間, 單位: s

     * @return

     */

    public Long expire(String key, int expireTime) {

        Jedis jedis = null;

        try {

            jedis = getJedis();

            return jedis.expire(key.getBytes(), expireTime);

        } catch (Exception e) {

            log.error("expire key:{} error", key, e);

            return null;

        } finally {

            close(jedis);

        }

    }

    /**

     * 獲取剩余時間

     *

     * @param key

     * @return

     */

    public Long ttl(String key) {

        Jedis jedis = null;

        try {

            jedis = getJedis();

            return jedis.ttl(key);

        } catch (Exception e) {

            log.error("ttl key:{} error", key, e);

            return null;

        } finally {

            close(jedis);

        }

    }

    private void close(Jedis jedis) {

        if (null != jedis) {

            jedis.close();

        }

    }

}

自定義注解@ApiIdempotent

package com.wangzaiplus.test.annotation;

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

/**

 * 在需要保證 接口冪等性 的Controller的方法上使用此注解

 */

@Target({ElementType.METHOD})

@Retention(RetentionPolicy.RUNTIME)

public @interface ApiIdempotent {

}

ApiIdempotentInterceptor攔截器

package com.wangzaiplus.test.interceptor;

import com.wangzaiplus.test.annotation.ApiIdempotent;

import com.wangzaiplus.test.service.TokenService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.method.HandlerMethod;

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.lang.reflect.Method;

/**

 * 接口冪等性攔截器

 */

public class ApiIdempotentInterceptor implements HandlerInterceptor {

    @Autowired

    private TokenService tokenService;

    @Override

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        if (!(handler instanceof HandlerMethod)) {

            return true;

        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        Method method = handlerMethod.getMethod();

        ApiIdempotent methodAnnotation = method.getAnnotation(ApiIdempotent.class);

        if (methodAnnotation != null) {

            check(request);// 冪等性校驗, 校驗通過則放行, 校驗失敗則拋出異常, 并通過統(tǒng)一異常處理返回友好提示

        }

        return true;

    }

    private void check(HttpServletRequest request) {

        tokenService.checkToken(request);

    }

    @Override

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}

TokenServiceImpl

package com.wangzaiplus.test.service.impl;

import com.wangzaiplus.test.common.Constant;

import com.wangzaiplus.test.common.ResponseCode;

import com.wangzaiplus.test.common.ServerResponse;

import com.wangzaiplus.test.exception.ServiceException;

import com.wangzaiplus.test.service.TokenService;

import com.wangzaiplus.test.util.JedisUtil;

import com.wangzaiplus.test.util.RandomUtil;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;

import org.apache.commons.lang3.text.StrBuilder;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service

public class TokenServiceImpl implements TokenService {

    private static final String TOKEN_NAME = "token";

    @Autowired

    private JedisUtil jedisUtil;

    @Override

    public ServerResponse createToken() {

        String str = RandomUtil.UUID32();

        StrBuilder token = new StrBuilder();

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

        jedisUtil.set(token.toString(), token.toString(), Constant.Redis.EXPIRE_TIME_MINUTE);

        return ServerResponse.success(token.toString());

    }

    @Override

    public void checkToken(HttpServletRequest request) {

        String token = request.getHeader(TOKEN_NAME);

        if (StringUtils.isBlank(token)) {// header中不存在token

            token = request.getParameter(TOKEN_NAME);

            if (StringUtils.isBlank(token)) {// parameter中也不存在token

                throw new ServiceException(ResponseCode.ILLEGAL_ARGUMENT.getMsg());

            }

        }

        if (!jedisUtil.exists(token)) {

            throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg());

        }

        Long del = jedisUtil.del(token);

        if (del <= 0) {

            throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg());

        }

    }

}

TestApplication

package com.wangzaiplus.test;

import com.wangzaiplus.test.interceptor.ApiIdempotentInterceptor;

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.Bean;

import org.springframework.web.cors.CorsConfiguration;

import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import org.springframework.web.filter.CorsFilter;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication

@MapperScan("com.wangzaiplus.test.mapper")

public class TestApplication  extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {

        SpringApplication.run(TestApplication.class, args);

    }

    /**

     * 跨域

     * @return

     */

    @Bean

    public CorsFilter corsFilter() {

        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();

        final CorsConfiguration corsConfiguration = new CorsConfiguration();

        corsConfiguration.setAllowCredentials(true);

        corsConfiguration.addAllowedOrigin("*");

        corsConfiguration.addAllowedHeader("*");

        corsConfiguration.addAllowedMethod("*");

        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);

        return new CorsFilter(urlBasedCorsConfigurationSource);

    }

    @Override

    public void addInterceptors(InterceptorRegistry registry) {

        // 接口冪等性攔截器

        registry.addInterceptor(apiIdempotentInterceptor());

        super.addInterceptors(registry);

    }

    @Bean

    public ApiIdempotentInterceptor apiIdempotentInterceptor() {

        return new ApiIdempotentInterceptor();

    }

}

OK, 目前為止, 校驗代碼準(zhǔn)備就緒, 接下來測試驗證

七、測試驗證

1、獲取token的控制器TokenController

package com.wangzaiplus.test.controller;

import com.wangzaiplus.test.common.ServerResponse;

import com.wangzaiplus.test.service.TokenService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

@RequestMapping("/token")

public class TokenController {

    @Autowired

    private TokenService tokenService;

    @GetMapping

    public ServerResponse token() {

        return tokenService.createToken();

    }

}

2、TestController, 注意@ApiIdempotent注解, 在需要冪等性校驗的方法上聲明此注解即可, 不需要校驗的無影響

package com.wangzaiplus.test.controller;

import com.wangzaiplus.test.annotation.ApiIdempotent;

import com.wangzaiplus.test.common.ServerResponse;

import com.wangzaiplus.test.service.TestService;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

@RequestMapping("/test")

@Slf4j

public class TestController {

    @Autowired

    private TestService testService;

    @ApiIdempotent

    @PostMapping("testIdempotence")

    public ServerResponse testIdempotence() {

        return testService.testIdempotence();

    }

}

3、獲取token

查看redis

4、測試接口安全性: 利用jmeter測試工具模擬50個并發(fā)請求, 將上一步獲取到的token作為參數(shù)

5、header或參數(shù)均不傳token, 或者token值為空, 或者token值亂填, 均無法通過校驗, 如token值為"abcd"

八、注意點(非常重要)

上圖中, 不能單純的直接刪除token而不校驗是否刪除成功, 會出現(xiàn)并發(fā)安全性問題, 因為, 有可能多個線程同時走到第46行, 此時token還未被刪除, 所以繼續(xù)往下執(zhí)行, 如果不校驗jedisUtil.del(token)的刪除結(jié)果而直接放行, 那么還是會出現(xiàn)重復(fù)提交問題, 即使實際上只有一次真正的刪除操作, 下面重現(xiàn)一下

稍微修改一下代碼:

再次請求

再看看控制臺

雖然只有一個真正刪除掉token, 但由于沒有對刪除結(jié)果進行校驗, 所以還是有并發(fā)問題, 因此, 必須校驗

九、總結(jié)

其實思路很簡單, 就是每次請求保證唯一性, 從而保證冪等性, 通過攔截器+注解, 就不用每次請求都寫重復(fù)代碼, 其實也可以利用spring aop實現(xiàn), 無所謂。

Github

https://github.com/wangzaiplus/springboot/tree/wxw
[我要糾錯]
[編輯:王振袢 &發(fā)表于江蘇]
關(guān)鍵詞: 概念 通俗 就是 一個 接口

來源:本文內(nèi)容搜集或轉(zhuǎn)自各大網(wǎng)絡(luò)平臺,并已注明來源、出處,如果轉(zhuǎn)載侵犯您的版權(quán)或非授權(quán)發(fā)布,請聯(lián)系小編,我們會及時審核處理。
聲明:江蘇教育黃頁對文中觀點保持中立,對所包含內(nèi)容的準(zhǔn)確性、可靠性或者完整性不提供任何明示或暗示的保證,不對文章觀點負責(zé),僅作分享之用,文章版權(quán)及插圖屬于原作者。

點個贊
0
踩一腳
0

您在閱讀:Springboot + redis + 注解 + 攔截器來實現(xiàn)接口冪等性校驗

Copyright©2013-2025 ?JSedu114 All Rights Reserved. 江蘇教育信息綜合發(fā)布查詢平臺保留所有權(quán)利

蘇公網(wǎng)安備32010402000125 蘇ICP備14051488號-3技術(shù)支持:南京博盛藍睿網(wǎng)絡(luò)科技有限公司

南京思必達教育科技有限公司版權(quán)所有   百度統(tǒng)計

主站蜘蛛池模板: 亚洲国产欧美精品 | 国产成人精品综合在线观看 | 日本全黄录像视频 | 成年视频免费 | 狠狠操天天操夜夜操 | 亚洲五月激情网 | 亚洲欧美精品在线 | 成人三级在线观看 | 男女毛片 | 久久男女| 久久精品一区 | 国产精品视频区 | 国产精品久久久久久久专区 | 亚洲一区免费在线 | 免费在线观看你懂的 | 欧美一级高清片欧美国产欧美 | 成人免费观看视频高清视频 | 国产精品页 | www.色偷偷.com| 欧美日韩视频一区二区在线观看 | 亚洲一级大黄大色毛片 | 午夜在线视频观看版 | a级毛片高清免费视频 | 亚洲日本中文字幕 | 香蕉视频久久 | 日韩国产免费 | 天天干天天射天天 | 无遮挡无删动漫肉在线观看 | 热re66久久精品国产99re | 久久亚洲精品中文字幕二区 | 亚洲欧美一区二区三区四区 | 黄色激情视频网站 | 99视频污在线观看 | 亚洲国产第一页 | 精品国产一区二区在线观看 | 九九九在线视频 | 精品九九人人做人人爱 | 99国产超薄丝袜足j在线观看 | 青青青在线视频播放 | 综合影院 | 乱系列h全文阅读小黄文肉 乱色美www女麻豆 |
最熱文章
最新文章
  • 阿里云上云鉅惠,云產(chǎn)品享最低成本,有需要聯(lián)系,
  • 卡爾蔡司鏡片優(yōu)惠店,鏡片價格低
  • 蘋果原裝手機殼