Spring Boot + Redis 实现接口幂等性 | 分布式开发必知!

2024-09-02 10:38

本文主要是介绍Spring Boot + Redis 实现接口幂等性 | 分布式开发必知!,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

点击上方“朱小厮的博客”,选择“设为星标

回复”1024“获取独家整理的学习资料

640?wx_fmt=jpeg

来源:http://tinyurl.com/y5k2sx5t

一、概念

幂等性, 通俗的说就是一个接口, 多次发起同一个请求, 必须保证操作只能执行一次 比如:

  • 订单接口, 不能多次创建订单

  • 支付接口, 重复支付同一笔订单只能扣一次钱

  • 支付宝回调接口, 可能会多次回调, 必须处理重复回调

  • 普通表单提交接口, 因为网络超时等原因多次点击提交, 只能成功一次 等等

二、常见解决方案

  1. 唯一索引 -- 防止新增脏数据

  2. token机制 -- 防止页面重复提交

  3. 悲观锁 -- 获取数据的时候加锁(锁表或锁行)

  4. 乐观锁 -- 基于版本号version实现, 在更新数据那一刻校验数据

  5. 分布式锁 -- redis(jedis、redisson)或zookeeper实现

  6. 状态机 -- 状态变更, 更新数据时判断状态

三、本文实现

本文采用第2种方式实现, 即通过redis + token机制实现接口幂等性校验

四、实现思路

为需要保证幂等性的每一次请求创建一个唯一标识 token, 先获取 token, 并将此 token存入redis, 请求接口时, 将此 token放到header或者作为请求参数请求接口, 后端接口判断redis中是否存在此 token:

  • 如果存在, 正常处理业务逻辑, 并从redis中删除此 token, 那么, 如果是重复请求, 由于 token已被删除, 则不能通过校验, 返回 请勿重复操作提示

  • 如果不存在, 说明参数不合法或者是重复请求, 返回提示即可

五、项目简介

  • springboot

  • redis

  • @ApiIdempotent注解 + 拦截器对请求进行拦截

  • @ControllerAdvice全局异常处理

  • 压测工具: jmeter

说明:

  • 本文重点介绍幂等性核心实现, 关于springboot如何集成redisServerResponseResponseCode等细枝末节不在本文讨论范围之内, 有兴趣的小伙伴可以查看作者的Github项目: https://github.com/wangzaiplus/springboot/tree/wxw

六、代码实现

pom

        <!-- Redis-Jedis -->	<dependency>	<groupId>redis.clients</groupId>	<artifactId>jedis</artifactId>	<version>2.9.0</version>	</dependency>	<!--lombok 本文用到@Slf4j注解, 也可不引用, 自定义log即可-->	<dependency>	<groupId>org.projectlombok</groupId>	<artifactId>lombok</artifactId>	<version>1.16.10</version>	</dependency>

JedisUtil

package com.wangzaiplus.test.util;	
import lombok.extern.slf4j.Slf4j;	
import org.springframework.beans.factory.annotation.Autowired;	
import org.springframework.stereotype.Component;	
import redis.clients.jedis.Jedis;	
import redis.clients.jedis.JedisPool;	
@Component	
@Slf4j	
public class JedisUtil {	@Autowired	private JedisPool jedisPool;	private Jedis getJedis() {	return jedisPool.getResource();	}	/**	* 设值	*	* @param key	* @param value	* @return	*/	public String set(String key, String value) {	Jedis jedis = null;	try {	jedis = getJedis();	return jedis.set(key, value);	} catch (Exception e) {	log.error("set key:{} value:{} error", key, value, e);	return null;	} finally {	close(jedis);	}	}	/**	* 设值	*	* @param key	* @param value	* @param expireTime 过期时间, 单位: s	* @return	*/	public String set(String key, String value, int expireTime) {	Jedis jedis = null;	try {	jedis = getJedis();	return jedis.setex(key, expireTime, value);	} catch (Exception e) {	log.error("set key:{} value:{} expireTime:{} error", key, value, expireTime, e);	return null;	} finally {	close(jedis);	}	}	/**	* 取值	*	* @param key	* @return	*/	public String get(String key) {	Jedis jedis = null;	try {	jedis = getJedis();	return jedis.get(key);	} catch (Exception e) {	log.error("get key:{} error", key, e);	return null;	} finally {	close(jedis);	}	}	/**	* 删除key	*	* @param key	* @return	*/	public Long del(String key) {	Jedis jedis = null;	try {	jedis = getJedis();	return jedis.del(key.getBytes());	} catch (Exception e) {	log.error("del key:{} error", key, e);	return null;	} finally {	close(jedis);	}	}	/**	* 判断key是否存在	*	* @param key	* @return	*/	public Boolean exists(String key) {	Jedis jedis = null;	try {	jedis = getJedis();	return jedis.exists(key.getBytes());	} catch (Exception e) {	log.error("exists key:{} error", key, e);	return null;	} finally {	close(jedis);	}	}	/**	* 设值key过期时间	*	* @param key	* @param expireTime 过期时间, 单位: s	* @return	*/	public Long expire(String key, int expireTime) {	Jedis jedis = null;	try {	jedis = getJedis();	return jedis.expire(key.getBytes(), expireTime);	} catch (Exception e) {	log.error("expire key:{} error", key, e);	return null;	} finally {	close(jedis);	}	}	/**	* 获取剩余时间	*	* @param key	* @return	*/	public Long ttl(String key) {	Jedis jedis = null;	try {	jedis = getJedis();	return jedis.ttl(key);	} catch (Exception e) {	log.error("ttl key:{} error", key, e);	return null;	} finally {	close(jedis);	}	}	private void close(Jedis jedis) {	if (null != jedis) {	jedis.close();	}	}	
}

自定义注解 @ApiIdempotent

package com.wangzaiplus.test.annotation;	
import java.lang.annotation.ElementType;	
import java.lang.annotation.Retention;	
import java.lang.annotation.RetentionPolicy;	
import java.lang.annotation.Target;	
/**	* 在需要保证 接口幂等性 的Controller的方法上使用此注解	*/	
@Target({ElementType.METHOD})	
@Retention(RetentionPolicy.RUNTIME)	
public @interface ApiIdempotent {	
}
  1. ApiIdempotentInterceptor拦截器

package com.wangzaiplus.test.interceptor;	
import com.wangzaiplus.test.annotation.ApiIdempotent;	
import com.wangzaiplus.test.service.TokenService;	
import org.springframework.beans.factory.annotation.Autowired;	
import org.springframework.web.method.HandlerMethod;	
import org.springframework.web.servlet.HandlerInterceptor;	
import org.springframework.web.servlet.ModelAndView;	
import javax.servlet.http.HttpServletRequest;	
import javax.servlet.http.HttpServletResponse;	
import java.lang.reflect.Method;	
/**	* 接口幂等性拦截器	*/	
public class ApiIdempotentInterceptor implements HandlerInterceptor {	@Autowired	private TokenService tokenService;	@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) {	tokenService.checkToken(request);	}	@Override	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {	}	@Override	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {	}	
}

TokenServiceImpl

package com.wangzaiplus.test.service.impl;	
import com.wangzaiplus.test.common.Constant;	
import com.wangzaiplus.test.common.ResponseCode;	
import com.wangzaiplus.test.common.ServerResponse;	
import com.wangzaiplus.test.exception.ServiceException;	
import com.wangzaiplus.test.service.TokenService;	
import com.wangzaiplus.test.util.JedisUtil;	
import com.wangzaiplus.test.util.RandomUtil;	
import lombok.extern.slf4j.Slf4j;	
import org.apache.commons.lang3.StringUtils;	
import org.apache.commons.lang3.text.StrBuilder;	
import org.springframework.beans.factory.annotation.Autowired;	
import org.springframework.stereotype.Service;	
import javax.servlet.http.HttpServletRequest;	
@Service	
public class TokenServiceImpl implements TokenService {	private static final String TOKEN_NAME = "token";	@Autowired	private JedisUtil jedisUtil;	@Override	public ServerResponse createToken() {	String str = RandomUtil.UUID32();	StrBuilder token = new StrBuilder();	token.append(Constant.Redis.TOKEN_PREFIX).append(str);	jedisUtil.set(token.toString(), token.toString(), Constant.Redis.EXPIRE_TIME_MINUTE);	return ServerResponse.success(token.toString());	}	@Override	public void checkToken(HttpServletRequest request) {	String token = request.getHeader(TOKEN_NAME);	if (StringUtils.isBlank(token)) {// header中不存在token	token = request.getParameter(TOKEN_NAME);	if (StringUtils.isBlank(token)) {// parameter中也不存在token	throw new ServiceException(ResponseCode.ILLEGAL_ARGUMENT.getMsg());	}	}	if (!jedisUtil.exists(token)) {	throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg());	}	Long del = jedisUtil.del(token);	if (del <= 0) {	throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg());	}	}	
}

TestApplication

package com.wangzaiplus.test;	
import com.wangzaiplus.test.interceptor.ApiIdempotentInterceptor;	
import org.mybatis.spring.annotation.MapperScan;	
import org.springframework.boot.SpringApplication;	
import org.springframework.boot.autoconfigure.SpringBootApplication;	
import org.springframework.context.annotation.Bean;	
import org.springframework.web.cors.CorsConfiguration;	
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;	
import org.springframework.web.filter.CorsFilter;	
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;	
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;	
@SpringBootApplication	
@MapperScan("com.wangzaiplus.test.mapper")	
public class TestApplication  extends WebMvcConfigurerAdapter {	public static void main(String[] args) {	SpringApplication.run(TestApplication.class, args);	}	/**	* 跨域	* @return	*/	@Bean	public CorsFilter corsFilter() {	final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();	final CorsConfiguration corsConfiguration = new CorsConfiguration();	corsConfiguration.setAllowCredentials(true);	corsConfiguration.addAllowedOrigin("*");	corsConfiguration.addAllowedHeader("*");	corsConfiguration.addAllowedMethod("*");	urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);	return new CorsFilter(urlBasedCorsConfigurationSource);	}	@Override	public void addInterceptors(InterceptorRegistry registry) {	// 接口幂等性拦截器	registry.addInterceptor(apiIdempotentInterceptor());	super.addInterceptors(registry);	}	@Bean	public ApiIdempotentInterceptor apiIdempotentInterceptor() {	return new ApiIdempotentInterceptor();	}	
}

OK, 目前为止, 校验代码准备就绪, 接下来测试验证

七、测试验证

获取 token的控制器 TokenController

package com.wangzaiplus.test.controller;	
import com.wangzaiplus.test.common.ServerResponse;	
import com.wangzaiplus.test.service.TokenService;	
import org.springframework.beans.factory.annotation.Autowired;	
import org.springframework.web.bind.annotation.GetMapping;	
import org.springframework.web.bind.annotation.RequestMapping;	
import org.springframework.web.bind.annotation.RestController;	
@RestController	
@RequestMapping("/token")	
public class TokenController {	@Autowired	private TokenService tokenService;	@GetMapping	public ServerResponse token() {	return tokenService.createToken();	}	
}

TestController, 注意 @ApiIdempotent注解, 在需要幂等性校验的方法上声明此注解即可, 不需要校验的无影响

package com.wangzaiplus.test.controller;	
import com.wangzaiplus.test.annotation.ApiIdempotent;	
import com.wangzaiplus.test.common.ServerResponse;	
import com.wangzaiplus.test.service.TestService;	
import lombok.extern.slf4j.Slf4j;	
import org.springframework.beans.factory.annotation.Autowired;	
import org.springframework.web.bind.annotation.PostMapping;	
import org.springframework.web.bind.annotation.RequestMapping;	
import org.springframework.web.bind.annotation.RestController;	
@RestController	
@RequestMapping("/test")	
@Slf4j	
public class TestController {	@Autowired	private TestService testService;	@ApiIdempotent	@PostMapping("testIdempotence")	public ServerResponse testIdempotence() {	return testService.testIdempotence();	}	
}

获取 token

640?wx_fmt=other

查看redis

640?wx_fmt=other

测试接口安全性: 利用jmeter测试工具模拟50个并发请求, 将上一步获取到的token作为参数

640?wx_fmt=other

640?wx_fmt=other

header或参数均不传token, 或者token值为空, 或者token值乱填, 均无法通过校验, 如token值为"abcd"

640?wx_fmt=other

八、注意点(非常重要)

640?wx_fmt=other

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

稍微修改一下代码:

640?wx_fmt=other

再次请求

640?wx_fmt=other

再看看控制台

640?wx_fmt=other

虽然只有一个真正删除掉token, 但由于没有对删除结果进行校验, 所以还是有并发问题, 因此, 必须校验

九、总结

其实思路很简单, 就是每次请求保证唯一性, 从而保证幂等性, 通过拦截器+注解, 就不用每次请求都写重复代码, 其实也可以利用spring aop实现。

想知道更多?描下面的二维码关注我

640?wx_fmt=png

相关推荐:

  • 《科普 | 明星公司之Netflix》

  • 《看我如何作死 | 将CPU、IO打爆》

  • 《看我如何作死 | 网络延迟、丢包、中断一个都没落下》

  • 《看我如何假死!》

  • 《这次我们看看阿里的人是如何蹂躏CPU的》

加技术群入口(备注:技术):>>>Learn More<<

免费资料入口(备注:1024):>>>Learn More<<

免费星球入口:>>>Free<<<

内推通道>>>>

点个"在看"呗^_^

这篇关于Spring Boot + Redis 实现接口幂等性 | 分布式开发必知!的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1129734

相关文章

Redis中6种缓存更新策略详解

《Redis中6种缓存更新策略详解》Redis作为一款高性能的内存数据库,已经成为缓存层的首选解决方案,然而,使用缓存时最大的挑战在于保证缓存数据与底层数据源的一致性,本文将介绍Redis中6种缓存更... 目录引言策略一:Cache-Aside(旁路缓存)策略工作原理代码示例优缺点分析适用场景策略二:Re

Flutter实现文字镂空效果的详细步骤

《Flutter实现文字镂空效果的详细步骤》:本文主要介绍如何使用Flutter实现文字镂空效果,包括创建基础应用结构、实现自定义绘制器、构建UI界面以及实现颜色选择按钮等步骤,并详细解析了混合模... 目录引言实现原理开始实现步骤1:创建基础应用结构步骤2:创建主屏幕步骤3:实现自定义绘制器步骤4:构建U

SpringBoot中四种AOP实战应用场景及代码实现

《SpringBoot中四种AOP实战应用场景及代码实现》面向切面编程(AOP)是Spring框架的核心功能之一,它通过预编译和运行期动态代理实现程序功能的统一维护,在SpringBoot应用中,AO... 目录引言场景一:日志记录与性能监控业务需求实现方案使用示例扩展:MDC实现请求跟踪场景二:权限控制与

Android开发环境配置避坑指南

《Android开发环境配置避坑指南》本文主要介绍了Android开发环境配置过程中遇到的问题及解决方案,包括VPN注意事项、工具版本统一、Gerrit邮箱配置、Git拉取和提交代码、MergevsR... 目录网络环境:VPN 注意事项工具版本统一:android Studio & JDKGerrit的邮

Android实现定时任务的几种方式汇总(附源码)

《Android实现定时任务的几种方式汇总(附源码)》在Android应用中,定时任务(ScheduledTask)的需求几乎无处不在:从定时刷新数据、定时备份、定时推送通知,到夜间静默下载、循环执行... 目录一、项目介绍1. 背景与意义二、相关基础知识与系统约束三、方案一:Handler.postDel

Python开发文字版随机事件游戏的项目实例

《Python开发文字版随机事件游戏的项目实例》随机事件游戏是一种通过生成不可预测的事件来增强游戏体验的类型,在这篇博文中,我们将使用Python开发一款文字版随机事件游戏,通过这个项目,读者不仅能够... 目录项目概述2.1 游戏概念2.2 游戏特色2.3 目标玩家群体技术选择与环境准备3.1 开发环境3

Java NoClassDefFoundError运行时错误分析解决

《JavaNoClassDefFoundError运行时错误分析解决》在Java开发中,NoClassDefFoundError是一种常见的运行时错误,它通常表明Java虚拟机在尝试加载一个类时未能... 目录前言一、问题分析二、报错原因三、解决思路检查类路径配置检查依赖库检查类文件调试类加载器问题四、常见

Java注解之超越Javadoc的元数据利器详解

《Java注解之超越Javadoc的元数据利器详解》本文将深入探讨Java注解的定义、类型、内置注解、自定义注解、保留策略、实际应用场景及最佳实践,无论是初学者还是资深开发者,都能通过本文了解如何利用... 目录什么是注解?注解的类型内置注编程解自定义注解注解的保留策略实际用例最佳实践总结在 Java 编程

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Java 实用工具类Spring 的 AnnotationUtils详解

《Java实用工具类Spring的AnnotationUtils详解》Spring框架提供了一个强大的注解工具类org.springframework.core.annotation.Annot... 目录前言一、AnnotationUtils 的常用方法二、常见应用场景三、与 JDK 原生注解 API 的