Springboot Redis 分布式锁

  • 首先搭建springboot1.X 项目

  • 倒入redis相关的JAR

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-redis</artifactId>
      </dependency>
    
  • 加锁

                    public boolean setNx(String lockKey, String requestId, int expireTime) {
                          boolean success = stringRedisTemplate.execute((RedisCallback<Boolean>) connection -> 
                          connection.set(lockKey.getBytes(), requestId.getBytes(), Expiration.from(expireTime, TimeUnit.SECONDS), RedisStringCommands.SetOption.SET_IF_ABSENT));
                          return success;
                   }
    
  • 释放锁

                            public boolean releaseDistributedLock(String lockKey, String requestId) {
                                String scriptStr = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                                DefaultRedisScript<Long> script = new DefaultRedisScript(scriptStr, Long.class);
                                List<String> keys = new ArrayList<>();
                                keys.add(lockKey);
                                Long result = stringRedisTemplate.execute(script, new StringRedisSerializer(), new RedisSerializer<Long>() {
                                    private final Charset charset = Charset.forName("UTF8");
                        
                                    @Override
                                    public byte[] serialize(Long aLong) throws SerializationException {
                                        return (aLong == null ? null : (aLong.toString()).getBytes(charset));
                                    }
                        
                                    @Override
                                    public Long deserialize(byte[] bytes) throws SerializationException {
                                        return (bytes == null ? null : Long.parseLong(new String(bytes, charset)));
                                    }
                                }, keys, requestId);
                                if (RELEASE_SUCCESS.equals(result)) {
                                    return true;
                                }
                                return false;
                            }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,859评论 18 139
  • 前言 分布式锁一般有三种实现方式:1. 数据库乐观锁;2. 基于Redis的分布式锁;3. 基于ZooKeeper...
    朦胧蜜桃阅读 491评论 1 0
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,935评论 6 342
  • 目前实现分布式锁的方式主要有数据库、Redis和Zookeeper三种,本文主要阐述利用Redis的相关命令来实现...
    Aldeo阅读 2,104评论 0 6
  • “线索?”八尾吕智迟疑道。他抬头望了望空中的云屿。这东西难不成还有什么渊源吗? 黑巫鸟微微颌首。“没错。阐里神社的...
    Hushmild阅读 703评论 0 2