zoukankan      html  css  js  c++  java
  • 在项目中,如何保证幂等性

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

    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提交禁止按钮,点击一次之后马上变成禁止点击按钮,或者使用节流方案禁止频繁点击
    1. 在服务器端,生成一个唯一的标识符,将它存入session, 同时将它写入表单的隐藏字段中,然后将表单页面发给浏览器, 用户录入信息后点击提交,在服务器端,获取表单中隐藏字段 的值,与session中的唯一标识符比较,相等说明是首次提交, 就处理本次请求,然后将session中的唯一标识符移除;不相等 说明是重复提交,就不再处理。
    1. 借助数据库, insert使用唯一索引 存储表单提交的的唯一标识
    1. 可将唯一标识使用分布式锁存入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);
            }
        }
    }
    
    
  • 相关阅读:
    react路由组件&&非路由组件
    react函数式组件(非路由组件)实现路由跳转
    react使用antd组件递归实现左侧菜单导航树
    【LeetCode】65. Valid Number
    【LeetCode】66. Plus One (2 solutions)
    【LeetCode】68. Text Justification
    【LeetCode】69. Sqrt(x) (2 solutions)
    【LeetCode】72. Edit Distance
    【LeetCode】73. Set Matrix Zeroes (2 solutions)
    【LeetCode】76. Minimum Window Substring
  • 原文地址:https://www.cnblogs.com/yunlongn/p/14609559.html
Copyright © 2011-2022 走看看