互联网并发与安全系列教程(08) - API接口幂等设计与实现

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: 互联网并发与安全系列教程(08) - API接口幂等设计与实现

实现思路:

  • 客户端每次在调用接口的时候,需要在请求头中,传递令牌参数,每次令牌只能用一次,有超时时间限定。
  • 一旦使用之后,就会被删除,这样可以有效防止重复提交。

本文目录结构:

l____1.BaseRedisService封装Redis

l____2. RedisTokenUtils工具类

l____3.自定义Api幂等注解和切面

l____4.幂等注解使用

l____5.封装生成token注解

l____6.改造ExtApiAopIdempotent

l____7.API接口保证幂等性

l____8. 页面防止重复提交

下面直接上代码

1.BaseRedisService封装Redis

@Component
public class BaseRedisService {
  @Autowired
  private StringRedisTemplate stringRedisTemplate;
  public void setString(String key, Object data, Long timeout) {
    if (data instanceof String) {
      String value = (String) data;
      stringRedisTemplate.opsForValue().set(key, value);
    }
    if (timeout != null) {
      stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
    }
  }
  public Object getString(String key) {
    return stringRedisTemplate.opsForValue().get(key);
  }
  public void delKey(String key) {
    stringRedisTemplate.delete(key);
  }
}

2. RedisTokenUtils工具类

@Component
public class RedisTokenUtils {
  private long timeout = 60 * 60;
  @Autowired
  private BaseRedisService baseRedisService;
  // 将token存入在redis
  public String getToken() {
    String token = "token" + System.currentTimeMillis();
    baseRedisService.setString(token, token, timeout);
    return token;
  }
  public boolean findToken(String tokenKey) {
    String token = (String) baseRedisService.getString(tokenKey);
    if (StringUtils.isEmpty(token)) {
      return false;
    }
    // token 获取成功后 删除对应tokenMapstoken
    baseRedisService.delKey(token);
    return true;
  }
}

3.自定义Api幂等注解和切面

1. 注解:

@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtApiIdempotent {
  String value();
}

2. 切面:

@Aspect
@Component
public class ExtApiAopIdempotent {
  @Autowired
  private RedisTokenUtils redisTokenUtils;
  @Pointcut("execution(public * com.itmayiedu.controller.*.*(..))")
  public void rlAop() {
  }
  @Around("rlAop()")
  public Object doBefore(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
    ExtApiIdempotent extApiIdempotent = signature.getMethod().getDeclaredAnnotation(ExtApiIdempotent.class);
    if (extApiIdempotent == null) {
      // 直接执行程序
      Object proceed = proceedingJoinPoint.proceed();
      return proceed;
    }
    // 代码步骤:
    // 1.获取令牌 存放在请求头中
    HttpServletRequest request = getRequest();
    String token = request.getHeader("token");
    if (StringUtils.isEmpty(token)) {
      response("参数错误!");
      return null;
    }
    // 2.判断令牌是否在缓存中有对应的令牌
    // 3.如何缓存没有该令牌的话,直接报错(请勿重复提交)
    // 4.如何缓存有该令牌的话,直接执行该业务逻辑
    // 5.执行完业务逻辑之后,直接删除该令牌。
    if (!redisTokenUtils.findToken(token)) {
      response("请勿重复提交!");
      return null;
    }
    Object proceed = proceedingJoinPoint.proceed();
    return proceed;
  }
  public HttpServletRequest getRequest() {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    return request;
  }
  public void response(String msg) throws IOException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletResponse response = attributes.getResponse();
    response.setHeader("Content-type", "text/html;charset=UTF-8");
    PrintWriter writer = response.getWriter();
    try {
      writer.println(msg);
    } catch (Exception e) {
    } finally {
      writer.close();
    }
  }
}

4.幂等注解使用

// 从redis中获取Token
@RequestMapping("/redisToken")
public String RedisToken() {
  return redisTokenUtils.getToken();
}
// 验证Token
@RequestMapping(value = "/addOrderExtApiIdempotent", produces = "application/json; charset=utf-8")
@ExtApiIdempotent
public String addOrderExtApiIdempotent(@RequestBody OrderEntity orderEntity, HttpServletRequest request) {
  int result = orderMapper.addOrder(orderEntity);
  return result > 0 ? "添加成功" : "添加失败" + "";
}

5.封装生成token注解

@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtApiToken {
}

6.改造ExtApiAopIdempotent

@Aspect
@Component
public class ExtApiAopIdempotent {
  @Autowired
  private RedisTokenUtils redisTokenUtils;
  @Pointcut("execution(public * com.itmayiedu.controller.*.*(..))")
  public void rlAop() {
  }
  // 前置通知转发Token参数
  @Before("rlAop()")
  public void before(JoinPoint point) {
    MethodSignature signature = (MethodSignature) point.getSignature();
    ExtApiToken extApiToken = signature.getMethod().getDeclaredAnnotation(ExtApiToken.class);
    if (extApiToken != null) {
      extApiToken();
    }
  }
  // 环绕通知验证参数
  @Around("rlAop()")
  public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
    ExtApiIdempotent extApiIdempotent = signature.getMethod().getDeclaredAnnotation(ExtApiIdempotent.class);
    if (extApiIdempotent != null) {
      return extApiIdempotent(proceedingJoinPoint, signature);
    }
    // 放行
    Object proceed = proceedingJoinPoint.proceed();
    return proceed;
  }
  // 验证Token
  public Object extApiIdempotent(ProceedingJoinPoint proceedingJoinPoint, MethodSignature signature)
      throws Throwable {
    ExtApiIdempotent extApiIdempotent = signature.getMethod().getDeclaredAnnotation(ExtApiIdempotent.class);
    if (extApiIdempotent == null) {
      // 直接执行程序
      Object proceed = proceedingJoinPoint.proceed();
      return proceed;
    }
    // 代码步骤:
    // 1.获取令牌 存放在请求头中
    HttpServletRequest request = getRequest();
    String valueType = extApiIdempotent.value();
    if (StringUtils.isEmpty(valueType)) {
      response("参数错误!");
      return null;
    }
    String token = null;
    if (valueType.equals(ConstantUtils.EXTAPIHEAD)) {
      token = request.getHeader("token");
    } else {
      token = request.getParameter("token");
    }
    if (StringUtils.isEmpty(token)) {
      response("参数错误!");
      return null;
    }
    if (!redisTokenUtils.findToken(token)) {
      response("请勿重复提交!");
      return null;
    }
    Object proceed = proceedingJoinPoint.proceed();
    return proceed;
  }
  public void extApiToken() {
    String token = redisTokenUtils.getToken();
    getRequest().setAttribute("token", token);
  }
  public HttpServletRequest getRequest() {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    return request;
  }
  public void response(String msg) throws IOException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletResponse response = attributes.getResponse();
    response.setHeader("Content-type", "text/html;charset=UTF-8");
    PrintWriter writer = response.getWriter();
    try {
      writer.println(msg);
    } catch (Exception e) {
    } finally {
      writer.close();
    }
  }
}

7.API接口保证幂等性

@RestController
public class OrderController {
  @Autowired
  private OrderMapper orderMapper;
  @Autowired
  private RedisTokenUtils redisTokenUtils;
  // 从redis中获取Token
  @RequestMapping("/redisToken")
  public String RedisToken() {
    return redisTokenUtils.getToken();
  }
  // 验证Token
  @RequestMapping(value = "/addOrderExtApiIdempotent", produces = "application/json; charset=utf-8")
  @ExtApiIdempotent(value = ConstantUtils.EXTAPIHEAD)
  public String addOrderExtApiIdempotent(@RequestBody OrderEntity orderEntity, HttpServletRequest request) {
    int result = orderMapper.addOrder(orderEntity);
    return result > 0 ? "添加成功" : "添加失败" + "";
  }
}

8. 页面防止重复提交

@Controller
public class OrderPageController {
  @Autowired
  private OrderMapper orderMapper;
  @RequestMapping("/indexPage")
  @ExtApiToken
  public String indexPage(HttpServletRequest req) {
    return "indexPage";
  }
  @RequestMapping("/addOrderPage")
  @ExtApiIdempotent(value = ConstantUtils.EXTAPIFROM)
  public String addOrder(OrderEntity orderEntity) {
    int addOrder = orderMapper.addOrder(orderEntity);
    return addOrder > 0 ? "success" : "fail";
  }
}


相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore     ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库 ECS 实例和一台目标数据库 RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
14天前
|
安全 Java API
第7章 Spring Security 的 REST API 与微服务安全(2024 最新版)(上)
第7章 Spring Security 的 REST API 与微服务安全(2024 最新版)
34 0
第7章 Spring Security 的 REST API 与微服务安全(2024 最新版)(上)
|
3天前
|
安全 Java Unix
如何开展API安全实现
【4月更文挑战第29天】安全编码培训、安全编码、静态检测。
|
4天前
|
存储 缓存 运维
DataWorks操作报错合集之DataWorks根据api,调用查询文件列表接口报错如何解决
DataWorks是阿里云提供的一站式大数据开发与治理平台,支持数据集成、数据开发、数据服务、数据质量管理、数据安全管理等全流程数据处理。在使用DataWorks过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
13 1
|
4天前
|
SQL 数据管理 API
数据管理DMS产品使用合集之阿里云DMS提供API接口来进行数据导出功能吗
阿里云数据管理DMS提供了全面的数据管理、数据库运维、数据安全、数据迁移与同步等功能,助力企业高效、安全地进行数据库管理和运维工作。以下是DMS产品使用合集的详细介绍。
|
4天前
|
运维 Serverless API
Serverless 应用引擎产品使用之在阿里函数计算中开启函数计算 API 接口如何解决
阿里云Serverless 应用引擎(SAE)提供了完整的微服务应用生命周期管理能力,包括应用部署、服务治理、开发运维、资源管理等功能,并通过扩展功能支持多环境管理、API Gateway、事件驱动等高级应用场景,帮助企业快速构建、部署、运维和扩展微服务架构,实现Serverless化的应用部署与运维模式。以下是对SAE产品使用合集的概述,包括应用管理、服务治理、开发运维、资源管理等方面。
103 6
|
7天前
|
前端开发 Java 测试技术
IDEA 版 API 接口神器来了,一键生成文档,贼香!
IDEA 版 API 接口神器来了,一键生成文档,贼香!
20 0
|
8天前
|
API 开发者
邮件API接口使用的方法和步骤
AOKSEND指南:了解和使用邮件API接口,包括选择适合的接口(如AOKSEND、Mailgun、SMTP),获取访问权限,配置发件人、收件人及邮件内容,调用接口发送邮件,并处理返回结果,以高效集成邮件功能。
|
11天前
|
Java API Android开发
[NDK/JNI系列04] JNI接口方法表、基础API与异常API
[NDK/JNI系列04] JNI接口方法表、基础API与异常API
12 0
|
12天前
|
XML JSON API
api接口的使用原理是什么?
总之,API接口的使用原理基于协议、规范和约定,允许不同的应用程序或系统之间进行通信和交互。这种通信方式使得开发人员能够轻松地利用外部服务或资源,从而实现更丰富的功能和服务。
15 0
|
14天前
|
安全 Java API
第7章 Spring Security 的 REST API 与微服务安全(2024 最新版)(下)
第7章 Spring Security 的 REST API 与微服务安全(2024 最新版)
22 0