依赖
<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:";
@Bean
public 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 {
@Autowired
private 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";
@Override
public 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));
return "1".equals(result.toString());
} catch (Exception e) {
return false;
}
}
@Override
public 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;
}
}
}