一、redis配置类:
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
@Data
public class JedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.database}")
private int database;
}
二、实现分布式锁工具类:
import redis.clients.jedis.Jedis;
/**
* @author:songwl
* @Date:2023/9/15 10:08
* @Description:
*/
public class AndawellRedisLock {
private Jedis jedis;
private String lockKey;
/**
* 锁自动过期时间,60秒
*/
private int expireTime = 60;
/**
* 重试时间,3秒
*/
private int retryTime = 3;
public AndawellRedisLock(String host, int port, int database,String lockKey, int expireTime) {
this.jedis = new Jedis(host, port);
jedis.select(database);
this.lockKey = lockKey;
this.expireTime = expireTime;
}
public AndawellRedisLock(String host, int port, int database, String lockKey) {
this.jedis = new Jedis(host, port);
jedis.select(database);
this.lockKey = lockKey;
}
/* public AndawellRedisLock(int database,String lockKey) {
this.jedis = new Jedis();
jedis.select(database);
this.lockKey = lockKey;
}*/
/**
* @author: songwl
* @Date: 2023/9/15 10:38
* @description:
*/
public boolean acquire() {
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime < retryTime * 1000) {
if (jedis.setnx(lockKey, "locked") == 1) {
jedis.expire(lockKey, expireTime);
//TimeLogUtil.printlnNowTime("内:"+Thread.currentThread().getName());
return true;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return false;
}
public void release() {
jedis.del(lockKey);
if(jedis!=null){
jedis.close();
}
}
public void close() {
if(jedis!=null){
jedis.close();
}
}
}
三、使用案例:
引入配置类:
@RequestMapping("/getLock")
public String getAndawellRedisLock() {
AndawellRedisLock andawellRedisLock = new AndawellRedisLock(jedisConfig.getHost(),jedisConfig.getPort(),jedisConfig.getDatabase(),"swlLock");
// 获取锁
if (andawellRedisLock.acquire()) {
try {
TimeUnit.SECONDS.sleep(10);
// 执行需要加锁的业务逻辑
System.out.println("获取到锁,执行业务逻辑");
} catch (Exception e){
} finally {
// 释放锁
andawellRedisLock.release();
}
} else {
System.out.println("获取锁失败,其他进程已经持有锁");
andawellRedisLock.close();
}
return "成功";
}