前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在项目中,如何保证幂等性

在项目中,如何保证幂等性

作者头像
云扬四海
发布2021-04-04 16:33:42
6750
发布2021-04-04 16:33:42
举报
文章被收录于专栏:云扬四海云扬四海云扬四海

在项目中,如何保证幂等性

1.什么是幂等

在我们编程中常见幂等
1)select查询天然幂等  
2)delete删除也是幂等,删除同一个多次效果一样 
3)update直接更新某个值的,幂等 
4)update更新累加操作的,非幂等 
5)insert非幂等操作,每次新增一条

2.产生原因

由于重复点击或者网络重发  eg:  
1)点击提交按钮两次;
2)点击刷新按钮;
3)使用浏览器后退按钮重复之前的操作,导致重复提交表单;
4)使用浏览器历史记录重复提交表单;
5)浏览器重复的HTTP请;
6)nginx重发等情况;
7)分布式RPC的try重发等;

3.解决方案:

1. 前端js提交禁止按钮,点击一次之后马上变成禁止点击按钮,或者使用节流方案禁止频繁点击

2. 在服务器端,生成一个唯一的标识符,将它存入session, 同时将它写入表单的隐藏字段中,然后将表单页面发给浏览器, 用户录入信息后点击提交,在服务器端,获取表单中隐藏字段 的值,与session中的唯一标识符比较,相等说明是首次提交, 就处理本次请求,然后将session中的唯一标识符移除;不相等 说明是重复提交,就不再处理。

3. 借助数据库, insert使用唯一索引 存储表单提交的的唯一标识

4. 可将唯一标识使用分布式锁存入redis中,抢锁提交, 如果抢到锁则请求成功,如果没抢到锁则提交失败

使用redisson实现分布式锁:

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.10.6</version>
</dependency>

属性配置 在 application.properites 资源文件中添加 redis 相关的配置项

spring:
  application:
    name: spring-cloud-product
  redis:
    port: 6379
    host: 127.0.0.1
    password:
    database: 0
    timeout: 2000

新建一个redisson-single.yml的配置文件 下面是单机配置

singleServerConfig:
  idleConnectionTimeout: 10000
  pingTimeout: 1000
  connectTimeout: 10000
  timeout: 3000
  retryAttempts: 3
  retryInterval: 1500
  reconnectionTimeout: 3000
  failedAttempts: 3
  password: null
  subscriptionsPerConnection: 5
  clientName: null
  address: "redis://127.0.0.1:6379"
  subscriptionConnectionMinimumIdleSize: 1
  subscriptionConnectionPoolSize: 50
  connectionMinimumIdleSize: 32
  connectionPoolSize: 64
  database: 0
  #在最新版本中dns的检查操作会直接报错 所以我直接注释掉了
  #dnsMonitoring: false
  dnsMonitoringInterval: 5000
threads: 0
nettyThreads: 0
codec: !<org.redisson.codec.JsonJacksonCodec> {}
transportMode : "NIO"

写一个RedissonConfig配置类 来配置你的redisson

/**
* @Description //TODO
 * @author yun
 * @date 2021/04/02
 */
@Configuration
public class RedssonConfig {
    @Bean(destroyMethod="shutdown")
    public RedissonClient redisson() throws IOException {
        RedissonClient redisson = Redisson.create(
                Config.fromYAML(new ClassPathResource("redisson-single.yml").getInputStream()));
        return redisson;
    }
}
/**
 * redis 方案
 *
 * @author yun
 * @date 2021/04/02
 */
@Aspect
@Configuration
public class LockMethodInterceptor {

    @Autowired
    public LockMethodInterceptor(RedissonClient redissonClient, CacheKeyGenerator cacheKeyGenerator) {
        this.redissonClient = redissonClient;
        this.cacheKeyGenerator = cacheKeyGenerator;
    }

    
    private final RedissonClient redissonClient;
    private final CacheKeyGenerator cacheKeyGenerator;


    @Around("execution(public * *(..)) && @annotation(com.yunlong.annotation.CacheLock)")
    public Object interceptor(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        CacheLock lock = method.getAnnotation(CacheLock.class);
        if (StringUtils.isEmpty(lock.prefix())) {
            throw new RuntimeException("lock key don't null...");
        }
        // 上下文中获取请求表单的唯一标识
        final String lockKey = cacheKeyGenerator.getLockKey(pjp);
        String value = UUID.randomUUID().toString();
  	RLock lockR = redissonClient.getLock(lockKey);
        try {
            // 假设上锁成功,但是设置过期时间失效,以后拿到的都是 false
            final boolean success = lockR.isLocked();
            if (!success) {
                throw new RuntimeException("重复提交");
            }
	     	lockR.unlock();
            try {
                return pjp.proceed();
            } catch (Throwable throwable) {
                throw new RuntimeException("系统异常");
            }
        } finally {
            lockR.unlock(lockKey);
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-04-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 在项目中,如何保证幂等性
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档