package com.sea.report.forms.product.config.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

import java.util.Collections;

/**
 * @Classname RedisLockUtil
 * @Description 我们至少要确保所的实现满足一下四个条件:
 * 1. 互斥性: 在任意时刻,只有一个客户端能持有锁
 * 2. 不会发生死锁:  即使有一个客户端在持有锁的期间崩溃而没有主动解锁, 也能保证后续其它
 * 客户端能加锁
 * 3. 具有容错性: 只要大部分的redis 节点正常运行,客户端就可以加锁和解锁
 * 4. 加锁和解锁必须是同一个客户端
 * @Date 2019/8/13 14:10
 * @Created by caibixiang
 */
public class RedisLockUtil {
    public static final String LOCK_SUCCESS = "OK";
    private static final Long RELEASE_SUCCESS = 1L;

    /**
     * @param lockKey    锁
     * @param requestId  请求标识
     * @param expireTime 超期时间
     * @return 是否获取成功
     */
    public static boolean tryLock(String lockKey, String requestId, int expireTime) {
        Jedis jedis = RedisClient.getJedisPoool().getResource();
        SetParams setParams = SetParams.setParams().px(expireTime).nx();
        String result = jedis.set(lockKey, requestId, setParams);
        if (LOCK_SUCCESS.equals(result))
            return true;
        return false;
    }


    /**
     * 用lua 脚本保证 一致性
     * @param lockKey
     * @param requestId
     * @return
     */
    public static boolean releaseLock(String lockKey, String requestId) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Jedis jedis = RedisClient.getJedisPoool().getResource();
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId))
        if (RELEASE_SUCCESS.equals(result))
            return true;
        return false;
    }


}
package com.sea.report.forms.product.config.redis;

import com.sea.report.forms.product.dto.PersonDto;
import com.sea.report.forms.product.util.MapToObject;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Map;

/**
 * @Classname RedisClient
 * @Description jedis client
 * @Date 2019/8/11 11:18
 * @Created by caibixiang
 */
@Component
public class RedisClient {
    

    public static JedisPool getJedisPoool() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(10);
        jedisPoolConfig.setMaxIdle(10);
        jedisPoolConfig.setMinIdle(10);
        jedisPoolConfig.setMaxWaitMillis(1000);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, "ip", 6379);
        return jedisPool;
    }


}

 

posted on 2019-08-13 17:15  蔡苗  阅读(651)  评论(0编辑  收藏  举报