当前位置:   article > 正文

Redis+token机制实现幂等性操作_token机制解决服务幂等性

token机制解决服务幂等性

Redis+Token机制实现幂等性操作

前言

 使用redis+token实现幂等性操作,防止表单的重复提交和一些其他重复请求操作。有些接口需要保证操作的唯一性,比如:订单接口(重复点击下单,只会生成一个订单号);支付接口(重复支付也只会扣一次款);表单接口等等…

一、实现幂等性操作的方法

  1. 唯一索引 – 防止新增脏数据
  2. token机制 – 防止页面重复提交
  3. 悲观锁 – 获取数据的时候加锁(锁表或锁行)
  4. 乐观锁 – 基于版本号version实现, 在更新数据那一刻校验数据
  5. 分布式锁 – redis(jedis、redisson)或zookeeper实现
  6. 状态机 – 状态变更, 更新数据时判断状态

本文使用token机制来实现幂等性操作

二、token机制简单流程图与原理(以表单提交为例)

这里以表单提交为例,大致的分析下流程:

  1. :tw-1f33a:在跳转到表单页面时,创建一个Token,存入redis中,并且保存这个token到表单页面中。
  2. :tw-1f349:现在进入了表单页面,在表单页面添加个隐藏域,放入token。
  3. :tw-1f369:表单正常提交,token也随之提交。
  4. :tw-1f352:拦截器开始拦截,获得表单提交的token并与redis中的token进行对比判断。
  5. :tw-1f35c:若判断通过,正常执行程序,并删除token。若判断不通过,说明这次提交的表单有问题,抛出异常,程序不再继续执行

【:tw-1f36c:情景:】用户提交了一个表单,但是网络比较慢,用户点了多次提交。此时第一个提交的内容token验证通过了,redis中token被销毁,剩下的请求虽然也携带了token,但是redis中已然没有了数据,剩下的请求验证全部不通过,请求被放弃…

操作演示:第一次正常提交,第二次模拟多次提交

三、项目实战

1、跳转页面

 	@GetMapping("/diary/newDiary")
    @ApiOperation("跳转到创建随笔页面")
	//这是一个简单的跳转页面controller,在跳转时生成一个token到前段页面去
    public ModelAndView toInsert(Model model){
        String newDiaryToken = redisUtils.getToken();
        model.addAttribute("newDiaryToken",newDiaryToken);
        return new ModelAndView("diary/insert");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2、token生成工具

/** 
    * @Description: 创建Token,怕麻烦的可以直接生成UUID作为toekn的key和value 
   * @Date: 2020/1/8 0008 
    */ 
    public String getToken(){
        String token_value = UUID.randomUUID().toString().replace("-","");
        int index = new Random().nextInt(5);
        String token_key = token_value.substring(0,index);
        try {
            redisTemplate.opsForValue().set(token_key,token_value);
            return token_key;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

3、表单页面加入隐藏项

<input type="hidden" th:value="${newDiaryToken}" name = "token">
  • 1

4、拦截器拦截url请求,验证token

package com.braisedpanda.my.blog.web.framework.filter;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;


/**
 * @program: my-blog
 * @description: token拦截器
 * 
 * @create: 2020-01-08 10:08
 **/
@Configuration
public class TokenInterceptorConfig implements WebMvcConfigurer {

    @Bean
    TokenInterceptor tokenInterceptor(){
        return new TokenInterceptor();
    }

    public void addInterceptors(InterceptorRegistry registry) {
        //拦截指定URL
        registry.addInterceptor(tokenInterceptor())
                .addPathPatterns("/admin/diary/insert/**");
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
package com.braisedpanda.my.blog.web.framework.filter;

import com.braisedpanda.my.blog.web.config.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: my-blog
 * @description:
 
 * @create: 2020-01-08 10:13
 **/
@Configuration
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //验证token
        String token = request.getParameter("token");
        String value = (String)redisUtils.get(token);
        if(!StringUtils.isEmpty(value) && value !=null && value.length()>0){
            redisUtils.del(token);
            log.info("处理请求成功.......");
            return true;
        }else {
            log.error("请勿重复提交表单.......");
            response.sendRedirect("/toError");
            return false;

        }
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

四、演示

跳转到新建表单页面

表单页面

redis中有了token

提交表单成功

token被删除

多次请求被抛弃

错误页面

参考与引用

1.Spring Boot + Token 实现接口幂等性 | 防止表单重复提交

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/425909
推荐阅读
相关标签
  

闽ICP备14008679号