最近遇到一些问题,表单重复提交,导致插入重复数据到数据库,这里查询一些通用的方案,自己都实践一下,以后好回顾。
实践代码项目 Github: https://github.com/h-dj/Spring-Learning/tree/master/repeat-submit
幂等含义
幂等(idempotent、idempotence)是一个数学与计算机学概念,常见于抽象代数中。
在编程中一个幂等操作的特点是其任意多次执行所产生的影响均与一次执行的影响相同。幂等函数,或幂等方法,是指可以使用相同参数重复执行,并能获得相同结果的函数。这些函数不会影响系统状态,也不用担心重复执行会对系统造成改变。--- 百科
简单理解:就是针对一个操作,不管做多少次,产生的效果都是一样的。
举例:
对于业务中需要考虑幂等性的地方一般都是接口的重复请求,重复请求是指同一个请求因为某些原因被多次提交。导致这个情况会有以下几种场景:
前端方面:
后台方面:
注意:
以下准备使用加入购物车为例,实现各个方案
复制代码123456789101112131415161718192021222324252627SQLDROP TABLE IF EXISTS `cart`;
CREATE TABLE `cart` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`product_id` bigint(20) DEFAULT NULL,
`product_name` varchar(500) DEFAULT NULL COMMENT '商品名称',
`product_sku_id` bigint(20) DEFAULT NULL,
`member_id` bigint(20) DEFAULT NULL,
`quantity` int(11) DEFAULT NULL COMMENT '购买数量',
`price` decimal(10,2) DEFAULT NULL COMMENT '添加到购物车的价格',
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_0900_ai_ci
COMMENT='购物车表';
DROP TABLE IF EXISTS `deduplicate`;
CREATE TABLE `deduplicate` (
id BIGINT(20) auto_increment NOT NULL,
unique_id varchar(100) NULL COMMENT '唯一ID',
CONSTRAINT deduplicate_PK PRIMARY KEY (id),
CONSTRAINT deduplicate_UN UNIQUE KEY (unique_id) -- 唯一索引
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_0900_ai_ci
COMMENT='去重表';
复制代码12345678910111213141516171819202122JAVA@RestController
@RequestMapping("/cart")
public class CartController {
@Autowired
private ICartService iCartService;
@ApiRepeatUniqueIdSubmit(keyExpression = "@cartController.getUserId()+'_'+#cartPO.getProductId() +'_'+#cartPO.getProductSkuId()")
@PostMapping(value = "/add")
public String add(@RequestBody CartPO cartPO) throws InterruptedException {
cartPO.setMemberId(getUserId());
iCartService.addCart(cartPO);
return "ok";
}
/**
* 获取当前登录用户ID
*
* @return
*/
public Long getUserId() {
return 1001L;
}
}
复制代码123456789101112131415161718192021222324252627JAVA@Transactional(rollbackFor = Exception.class)
@Override
public void addCart(CartPO cartPO) throws InterruptedException {
LambdaQueryWrapper<CartPO> queryWrapper = Wrappers.<CartPO>lambdaQuery()
.eq(CartPO::getMemberId, cartPO.getMemberId())
.eq(CartPO::getProductId, cartPO.getProductId())
.eq(CartPO::getProductSkuId, cartPO.getProductSkuId());
//查询商品,已添加到购物车的,就增加数量即可(业务逻辑幂等)
//因为 select 和 save 操作不是串行执行的,可能有两个线程同时查询到商品没有添加到购物车
//然后同一个商品被两个线程分别入库了,导致购物车出现相同商品的两条记录
List<CartPO> list = this.list(queryWrapper);
//模拟耗时
TimeUnit.SECONDS.sleep(1);
if (list == null || list.isEmpty()) {
//添加到购物车
this.save(cartPO);
} else {
CartPO updateCartPO = list.get(0);
//数量加一
LambdaUpdateWrapper<CartPO> updateWrapper = Wrappers.<CartPO>lambdaUpdate()
.eq(CartPO::getId, updateCartPO.getId())
.setSql("quantity = quantity + 1");
this.update(updateWrapper);
}
}
复制代码1234567891011121314151617JAVA@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface ApiRepeatUniqueIdSubmit {
/**
* 唯一key,支持Spring EL 表达式
*
* @return
* @ 符号引用 Spring 注册的bean
* # 符合引用方法上的参数
* param?.id 其中? 是避免param为空时,发生空指针异常
* @see <a>https://docs.spring.io/spring-framework/docs/3.0.x/reference/expressions.html</a>
*/
String keyExpression();
}
复制代码123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657JAVA@Component
@Aspect
public class ApiRepeatSubmitUniqueIdAspect {
@Autowired
private ApplicationContext applicationContext;
@Autowired
private IDeduplicateService iDeduplicateService;
@Pointcut("@annotation(cn.hdj.repeatsubmit.aspect.ApiRepeatUniqueIdSubmit)")
public void pointCut() {
}
@Transactional(rollbackFor = Exception.class)
@Around("pointCut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
Signature signature = joinPoint.getSignature();
MethodSignature msig = (MethodSignature) signature;
Method targetMethod = msig.getMethod();
ApiRepeatUniqueIdSubmit apiRepeatSubmit = targetMethod.getAnnotation(ApiRepeatUniqueIdSubmit.class);
String keyExpression = apiRepeatSubmit.keyExpression();
Map<String, Object> argMap = SpringElUtil.getArgMap(joinPoint);
//获取业务参数,组成唯一ID
String uniqueId = SpringElUtil.<String>createElBuilder()
.setArgMap(argMap)
.setBeanFactory(applicationContext)
.setTarget(String.class)
.setKeyExpression(keyExpression)
.build();
LambdaQueryWrapper<DeduplicatePO> queryWrapper = Wrappers.<DeduplicatePO>lambdaQuery()
.eq(DeduplicatePO::getUniqueId, uniqueId);
long count = this.iDeduplicateService.count(queryWrapper);
if (count > 0) {
throw new DuplicateKeyException("不要重复提交!");
}
//插入去重表
DeduplicatePO deduplicatePO = new DeduplicatePO();
deduplicatePO.setUniqueId(uniqueId);
try {
this.iDeduplicateService.save(deduplicatePO);
} catch (Exception e) {
throw new DuplicateKeyException("不要重复提交!");
}
Object proceed = joinPoint.proceed();
//执行完删除
this.iDeduplicateService.removeById(deduplicatePO);
return proceed;
}
}
分布式锁可以使用 Redis 和 Zookeeper ,更多关于 Redis 和 Zookeeper 的使用 请自行查阅资料。以下使用 Redis 来实现分布式锁
复制代码12345XML<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.16.6</version>
</dependency>
复制代码1234567891011121314YAMLspring:
redis:
# https://github.com/redisson/redisson/wiki/2.-Configuration
database: '0'
host: '127.0.0.1'
port: '6379'
#password: '123456'
# ssl:
# timeout:
# cluster:
# nodes:
# sentinel:
# master:
# nodes:
复制代码1234567891011121314151617181920JAVA//创建锁
RLock lock = this.redissonClient.getLock(LOCK_PREFIX + uniqueId);
//判断是否被抢占了锁
if (lock.isLocked()) {
throw new DuplicateKeyException("不要重复提交!");
}
//尝试获取锁, 默认30秒会超时过期, 并启动线程监听,自动续签
//当客户端异常,终止了续签线程,超时后会删除锁,避免发生死锁
//如果自己手动设置了超时过期时间,则不会启动线程监听,自动续签
if (lock.tryLock()) {
try {
return joinPoint.proceed();
} finally {
//释放锁
lock.unlock();
}
}
throw new DuplicateKeyException("不要重复提交!");
复制代码1234567891011121314151617181920212223242526272829303132333435363738394041JAVA@Service
public class TokenServiceImpl implements TokenService {
public static final String TOKEN_PREFIX = "token_idempotent";
public static final String TOKEN_HEADER_NAME = "x-token";
public static final Long TOKEN_EXPIRE_TIME = 5 * 60L;
@Autowired
private RedissonClient redissonClient;
@Override
public String createToken() {
String ID = UUID.randomUUID().toString();
RBucket<String> bucket = this.redissonClient.<String>getBucket(String.format("%s:%s", TOKEN_PREFIX, ID), StringCodec.INSTANCE);
//默认超时5分钟
bucket.trySet(ID, TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
return ID;
}
@Override
public boolean checkToken(HttpServletRequest request) {
// 从请求头中获取token信息
String token = request.getHeader(TOKEN_HEADER_NAME);
if (!StringUtils.hasLength(token)) {
//从参数中获取token值
token = request.getParameter(TOKEN_HEADER_NAME);
}
if (!StringUtils.hasLength(token)) {
throw new DuplicateKeyException("重复提交,提交失败");
}
RBucket<String> bucket = this.redissonClient.getBucket(String.format("%s:%s", TOKEN_PREFIX, token), StringCodec.INSTANCE);
//获取,并删除
String ID = bucket.getAndDelete();
//不存在,则重复提交
if (ID == null) {
throw new DuplicateKeyException("重复提交,提交失败");
}
return true;
}
}
复制代码1234567891011121314151617JAVA@Component
@Aspect
public class ApiRepeatSubmitTokenAspect {
@Autowired
private TokenService tokenService;
@Autowired
private HttpServletRequest request;
@Pointcut("@annotation(cn.hdj.repeatsubmit.aspect.ApiRepeatTokenSubmit)")
public void pointCut() {
}
@Before("pointCut()")
public void Before(JoinPoint joinPoint) {
tokenService.checkToken(request);
}
}
复制代码12345678JAVASCRIPT$.ajax({
type: "GET",
url: "/token/create",
contentType:'application/json',
success: function(token){
sessionStorage.setItem('x-token',token);
}
});
复制代码1234567891011121314151617181920212223242526JAVASCRIPT$("#addCart").click(function(){
//按钮置灰
$("#addCart").attr('disabled','disabled');
$.ajax({
type: "POST",
url: "/cart/add",
headers:{
//携带token
'x-token':sessionStorage.getItem('x-token')
},
data: JSON.stringify({
productId: $('input[name=product_id]').val(),
productSkuId: $('input[name=product_sku_id]').val(),
productName: $('input[name=product_name]').val(),
price: $('input[name=price]').val(),
quantity: $('input[name=quantity]').val()
}),
contentType:'application/json',
success: function(msg){
console.log(msg)
},
complete: function(msg){
$("#addCart").removeAttr('disabled');
}
});
});
以上是较为常见通用的幂等方案,但实际业务可能比较个性化,需要跟业务结合进行考虑,采用合适的方法或结合使用,例如:
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。