Redis+Token实现接口幂等性

  • 请求前创建一个唯一标识token, 先获取token, 并将此token存入redis
  • 请求接口时, 将此token放到header或者作为请求参数请求接口, 后端接口判断redis中是否存在此token
  • 如果存在, 正常处理业务逻辑, 并从redis中删除此token
  • 如果不存在, 说明参数不合法或者是重复请求, 返回提示即可

代码实现

RedisUtil

package com.smartMap.media.common.apiIdempotent.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @description
 */
@Component
public class RedisUtil {

    private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 设值
     * @param key
     * @param value
     * @return
     */
    public void set(String key, String value) {
        logger.info("set key:{} value:{}", key, value);
        stringRedisTemplate.opsForValue().set(key,value);
    }

    /**
     * 设值
     * @param key
     * @param value
     * @param expireTime 过期时间, 单位: s
     * @return
     */
    public void set(String key, String value, int expireTime) {
        logger.info("set key:{} value:{} expireTime:{}", key, value, expireTime);
        stringRedisTemplate.opsForValue().set(key,value, expireTime,TimeUnit.SECONDS);
    }

    /**
     * 取值
     * @param key
     * @return
     */
    public String get(String key) {
        logger.info("get key:{}", key);
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 删除key
     * @param key
     * @return
     */
    public Boolean del(String key) {
        if (exists(key)) {
            return stringRedisTemplate.delete(key);
        } else {
            logger.error("del key:{}", key+" 不存在");
            return false;
        }

    }

    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public Boolean exists(String key) {
        Boolean exists = stringRedisTemplate.hasKey(key);
        logger.info("exists key:{} hasKey:{}", key, exists);
        return exists;
    }
}

自定义注解 @ApiIdempotent

package com.smartMap.media.common.apiIdempotent.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @description
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiIdempotent {

}

token接口 ApiIdempotentTokenService

package com.smartMap.media.common.apiIdempotent.service;

import com.smartMap.media.common.utils.R;

import javax.servlet.http.HttpServletRequest;

/**
 * @description
 */
public interface ApiIdempotentTokenService {

    R createToken();

    void checkToken(HttpServletRequest request);
}

token接口实现类 ApiIdempotentTokenServiceImpl

package com.smartMap.media.common.apiIdempotent.service.impl;

import com.smartMap.media.common.apiIdempotent.common.Constant;
import com.smartMap.media.common.apiIdempotent.common.ResponseCode;
import com.smartMap.media.common.apiIdempotent.service.ApiIdempotentTokenService;
import com.smartMap.media.common.apiIdempotent.utils.RedisUtil;
import com.smartMap.media.common.exception.RRException;
import com.smartMap.media.common.utils.R;
import com.smartMap.media.common.utils.UuidUtils;
import org.apache.commons.lang.text.StrBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @description
 */
@Service("apiIdempotentTokenService")
public class ApiIdempotentTokenServiceImpl implements ApiIdempotentTokenService {

    private static final String API_IDEMPOTENT_TOKEN_NAME = "apiIdempotentToken";

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public R createToken() {
        String str = UuidUtils.randomUUID();
        StrBuilder token = new StrBuilder();
        token.append(Constant.Redis.TOKEN_PREFIX).append(str);
        redisUtil.set(token.toString(), token.toString(), Constant.Redis.EXPIRE_TIME_FIVE_MINUTE);
        return R.ok().put("token",token.toString());
    }

    @Override
    public void checkToken(HttpServletRequest request) {
        String token = request.getHeader(API_IDEMPOTENT_TOKEN_NAME);
        // header中不存在token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(API_IDEMPOTENT_TOKEN_NAME);
            // parameter中也不存在token
            if (StringUtils.isBlank(token)) {
                throw new RRException(ResponseCode.ILLEGAL_ARGUMENT.getMsg(),ResponseCode.ILLEGAL_ARGUMENT.getCode());
            }
        }

        if (!redisUtil.exists(token)) {
            throw new RRException(ResponseCode.REPETITIVE_OPERATION.getMsg(),ResponseCode.REPETITIVE_OPERATION.getCode());
        }

        Boolean del = redisUtil.del(token);
        if (!del) {
            throw new RRException(ResponseCode.REPETITIVE_OPERATION.getMsg(),ResponseCode.REPETITIVE_OPERATION.getCode());
        }
    }
}

拦截器 ApiIdempotentInterceptor

package com.smartMap.media.common.apiIdempotent.interceptor;

import com.smartMap.media.common.apiIdempotent.annotation.ApiIdempotent;
import com.smartMap.media.common.apiIdempotent.service.ApiIdempotentTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @description
 */
@Component
public class ApiIdempotentInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private ApiIdempotentTokenService apiIdempotentTokenService;

    @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);
        }

        return true;
    }

    private void check(HttpServletRequest request) {
        apiIdempotentTokenService.checkToken(request);
    }
}

拦截器注册 WebConfig

package com.smartMap.media.common.config;

import com.smartMap.media.common.apiIdempotent.interceptor.ApiIdempotentInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @description
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private ApiIdempotentInterceptor apiIdempotentInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(apiIdempotentInterceptor);
    }
}

测试验证 controller

package com.smartMap.media.modules.mobile.controller;

import com.smartMap.media.common.apiIdempotent.annotation.ApiIdempotent;
import com.smartMap.media.common.apiIdempotent.service.ApiIdempotentTokenService;
import com.smartMap.media.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description
 */
@RestController
@RequestMapping("/mobile/test")
public class TestController {

    @Autowired
    private ApiIdempotentTokenService apiIdempotentTokenService;

    /**
     * 获取token
     * @return
     */
    @RequestMapping("getToken")
    public R getToken() {
        return apiIdempotentTokenService.createToken();
    }
    
    /**
     * 测试接口幂等性, 在需要幂等性校验的方法上声明此注解即可
     * @return
     */
    @ApiIdempotent
    @RequestMapping("testIdempotence")
    public R testIdempotence() {
        return R.ok("测试接口幂等性");
    }
}

在这里插入图片描述

上图中, 不能单纯的直接删除token而不校验是否删除成功, 会出现并发安全性问题, 因为, 有可能多个线程同时走到第51行, 此时token还未被删除, 所以继续往下执行, 如果不校验redisUtil.del(token)的删除结果而直接放行, 那么还是会出现重复提交问题, 即使实

际上只有一次真正的删除操作

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值