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 at least we want to ensure that it meets the four conditions: * 1. mutually exclusive: at any given time, only one client can hold a lock * 2. deadlock will not happen: even if there is a client support no active collapse unlocked, but also to ensure the lock during other subsequent * client can lock * 3. the fault tolerant: as long as most of the node redis normal operation, the client can lock and unlock * 4. lock and must be unlocked with a client * @date 2019/8/13 14:10 * @Created by caibixiang * / public class RedisLockUtil { public static Final String LOCK_SUCCESS = "the OK"; Private static Final Long RELEASE_SUCCESS = 1L ; / ** * @param lockKey lock * @param the requestId request identifier * @param expireTime expiration time * @return whether acquisition success * / public static Boolean tryLock (lockKey String, String the requestId, int expireTime ) { jedis jedis = RedisClient.getJedisPoool () the getResource ();. setParams with 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; } }