本文主要是介绍Springboot-Jedis实现分布式锁,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
依赖
<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>3.3.0</version></dependency>
配置类
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig {public static final String KEY_PREFIX ="xxx-service:";@Beanpublic JedisPool jedisPool(RedisProperties properties) {JedisPoolConfig config = new JedisPoolConfig();config.setMaxTotal(128);config.setMaxIdle(16);config.setMinIdle(16);return new JedisPool(config, properties.getHost(), properties.getPort(), 2000, properties.getPassword());}
}
工具类
@Service
@Qualifier("jedisService")
public class JedisServiceImpl implements ILockService {@Autowiredprivate JedisPool jedisPool;private static final String RELEASE_LOCK_LUA_SCRIPT ="if redis.call('get', KEYS[1]) == ARGV[1] then " +"return redis.call('del', KEYS[1]) " +"else " +"return 0 " +"end";private static final String TRY_LOCK_LUA_SCRIPT ="if redis.call('setNx', KEYS[1], ARGV[1]) then " +" if redis.call('get', KEYS[1]) == ARGV[1] then " +" return redis.call('expire', KEYS[1], ARGV[2]) " +" else " +" return 0 " +" end " +"else " +" return 0 " +"end";@Overridepublic boolean tryLock(String lockKey, String lockValue, long expireSeconds) {lockKey= RedisConfig.KEY_PREFIX+lockKey;try (Jedis jedis = jedisPool.getResource()) {Object result = jedis.eval(TRY_LOCK_LUA_SCRIPT,1,lockKey,lockValue,String.valueOf(expireSeconds));// Redis会返回Long类型的结果return "1".equals(result.toString());} catch (Exception e) {//打印日志;return false;}}@Overridepublic boolean releaseLock(String lockKey, String lockValue) {lockKey= RedisConfig.KEY_PREFIX+lockKey;try (Jedis jedis = jedisPool.getResource()) {Object result = jedis.eval(RELEASE_LOCK_LUA_SCRIPT,1,lockKey,lockValue);return "1".equals(result.toString());} catch (Exception e) {//打印日志;return false;}}
}
这篇关于Springboot-Jedis实现分布式锁的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!