springboot结合redis防止重复提交订单


项目地址:

利用redis+token+拦截器+注解(只在需要防止重复的接口上添加该注解即可)实现防止重复订单,在跳转到提交订单的页面时就通过getNotRepeatToken获取到本次订单的唯一标识(以业务加上用户id加上uuid作为key)存入redis,并返回给前端。在提交订单时,将该标识设置在请求头中,第一次提交订单时,在redis中删除该key。后续再次提交订单时redis中已经不存在该key,则给出重复提交订单的友好提示。
springboot 拦截器注入service为null的问题,可以通过bean工厂来完成手动注入。

定义注解和拦截器

注解:NotRepeat.java

package com.demo.aop;

import java.lang.annotation.*;

/**
 * 禁止重复提交的注解
 * @Author: zlw
 * @Date: 2019/7/16 10:55
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NotRepeat {
}

拦截器:NotRepeatInterceptor.java

package com.demo.config;

import com.demo.aop.NotRepeat;
import com.demo.enums.ExceptionEnum;
import com.demo.exception.ServiceException;
import com.demo.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * @Author: zlw
 * @Date: 2019/7/16 11:09
 */
@Slf4j
public class NotRepeatInterceptor implements HandlerInterceptor {


    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //解决service为null   因为拦截器是在springContext之前加载的,通过@component注解的bean还没有注入到容器中
        if (redisUtils == null) {
            BeanFactory factory= WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
             redisUt
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值