专栏名称: 武哥聊编程
这里有技术,有段子,有生活,也有资源,要不然怎么叫 “私房菜” 呢?
目录
相关文章推荐
三峡小微  ·  媒体聚焦:梯级电站保供很给力 ... ·  13 小时前  
三峡小微  ·  三峡集团与长江水利委员会座谈 ·  13 小时前  
三峡小微  ·  大国重器前的宣讲:单单的三峡情 ·  3 天前  
51好读  ›  专栏  ›  武哥聊编程

瞬间几千次的重复提交,我用 SpringBoot+Redis 扛住了

武哥聊编程  · 公众号  ·  · 2020-02-27 08:45

正文

作者 | 慕容千语
来源 | http://suo.im/5PaEZI

在实际的开发项目中, 一个对外暴露的接口往往会面临,瞬间大量的重复的请求提交 ,如果想过滤掉重复请求造成对业务的伤害,那就需要 实现幂等

我们来解释一下幂等的概念:

任意多次执行所产生的影响均与一次执行的影响相同 按照这个含义,最终的含义就是 对数据库的影响只能是一次性的,不能重复处理。

如何保证其幂等性,通常有以下手段:

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

  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.     * 写入缓存设置时效时间

  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.     * 判断缓存中是否有对应的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.     * 删除对应的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

自定义一个注解,定义此注解的主要目的是把它添加在需要实现幂等的方法上,凡是某个方法注解了它,都会实现自动幂等。 后台利用反射如果扫描到这个注解,就会处理这个方法实现自动幂等,使用元注解ElementType.METHOD表示它只能放在方法上,etentionPolicy.RUNTIME表示它在运行时

  1. @Target({ElementType.METHOD})

  2. @Retention(RetentionPolicy.RUNTIME)

  3. public@interfaceAutoIdempotent{

  4. }

三、token创建和检验

1、 token服务接口

我们新建一个接口,创建token服务,里面主要是两个方法,一个用来创建token,一个用来验证token。 创建token主要产生的是一个字符串,检验token的话主要是传达request对象,为什么要传request对象呢? 主要作用就是获取header里面的token,然后检验,通过抛出的Exception来获取具体的报错信息返回给前端。

  1. publicinterfaceTokenService{

  2.    /**

  3.     * 创建token

  4.     * @return

  5.     */

  6.    public  String createToken();

  7.    /**

  8.     * 检验token

  9.     * @param request

  10.     * @return

  11.     */

  12.    publicboolean checkToken(HttpServletRequest request) throwsException;

  13. }

2、 token的服务实现类

token引用了redis服务,创建token采用随机算法工具类生成随机uuid字符串,然后放入到redis中(为了防止数据的冗余保留,这里设置过期时间为10000秒,具体可视业务而定),如果放入成功,最后返回这个token值。 checkToken方法就是从header中获取token到值(如果header中拿不到,就从paramter中获取),如若不存在,直接抛出异常。 这个异常信息可以被拦截器捕捉到,然后返回给前端。

  1. @Service

  2. publicclassTokenServiceImplimplementsTokenService{

  3.    @Autowired

  4.    privateRedisService redisService;

  5.    /**

  6.     * 创建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.     * 检验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配置类,实现WebMvcConfigurerAdapter,主要作用就是添加autoIdempotentInterceptor到配置类中,这样我们到拦截器才能生效,注意使用@Configuration注解,这样在容器启动是时候就可以添加进入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到注解到方法,然后调用tokenService的checkToken()方法校验token是否正确,如果捕捉到异常就将异常信息渲染成json返回给前端

  1. /**

  2. * 拦截器

  3. */

  4. @Component

  5. publicclassAutoIdempotentInterceptorimplementsHandlerInterceptor{

  6.    @Autowired

  7.    privateTokenService tokenService;

  8.    /**

  9.     * 预处理

  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标记的扫描

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

  26.        if(methodAnnotation != null) {

  27.            try{

  28.                return tokenService.checkToken(request);// 幂等性校验, 校验通过则放行, 校验失败则抛出异常, 并通过统一异常处理返回友好提示

  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,否则会被拦截一切请求

  36.        returntrue;

  37.    }

  38.    @Override

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

  40.    }

  41.    @Override

  42.    







请到「今天看啥」查看全文