Redis分布式锁java版_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Redis分布式锁java版

Redis分布式锁java版

 2018/11/9 15:27:50  mulingya  程序员俱乐部  我要评论(0)
  • 摘要:一、引入maven依赖<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.9.0</version></dependency><dependency><groupId>org.springframework.data</groupId><
  • 标签:Java
一、引入maven依赖

class="java"><dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.8.16.RELEASE</version>
</dependency>

二、spring-data-jedis命令封装

private StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();

public Object eval(final String script, final List<String> keys, final List<String> args) {
        return stringRedisTemplate.execute(new RedisCallback<Object>() {
            public Object doInRedis(RedisConnection connection) {
                Jedis jedis = (Jedis) connection.getNativeConnection();
                return jedis.eval(script, keys, args);
            }
        }, true);
    }

    public String set(final String key, final String value, final String nxxx, final String expx, final long time) {
        return stringRedisTemplate.execute(new RedisCallback<String>() {
            public String doInRedis(RedisConnection connection) {
                Jedis jedis = (Jedis) connection.getNativeConnection();
                return jedis.set(key, value, nxxx, expx, time);
            }
        }, true);
    }

三、分布式锁封装

    private static final String LOCK_SUCCESS = "OK";
    private static final String IF_ABSENT = "NX";
    // private static final String NOT_ABSENT = "XX";
    private static final String EXPIRE_TIME_PX = "PX"; // 毫秒
    // private static final String EXPIRE_TIME_EX = "EX"; // 秒
    private static final Long RELEASE_SUCCESS = 1L;

    /**
     * 尝试获取分布式锁
     * 
     * @param key
     * @param requestId 请求ID
     * @param expired
     * @return
     */
    protected boolean tryLock(String key, String requestId, long expired) {
        String result = stringRedisTemplate.set(key, requestId, IF_ABSENT, EXPIRE_TIME_PX, expired);

        if (LOCK_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }

    /**
     * 释放分布式锁
     * 
     * @param key
     * @param requestId 请求ID
     * @return
     */
    protected boolean unlock(String key, String requestId) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = stringRedisTemplate.eval(script, Collections.singletonList(key), Collections.singletonList(requestId));

        if (RELEASE_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }
上一篇: Java资源免费分享,每日一更新,找到你心仪的吧 下一篇: 没有下一篇了!
发表评论
用户名: 匿名