1、导入pom.xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.2.9.RELEASE
com.lian
springboot
0.0.1-SNAPSHOT
SpringBootDemo
war
1.8
1.2.5
2.1.4
org.springframework.boot
spring-boot-starter-web
com.github.pagehelper
pagehelper-spring-boot-starter
1.3.1
org.mybatis.spring.boot
mybatis-spring-boot-starter
${mybatis.spring.boot.version}
org.springframework.boot
spring-boot-devtools
runtime
true
mysql
mysql-connector-java
runtime
com.alibaba
druid-spring-boot-starter
${druid.version}
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
com.alibaba
fastjson
1.2.72
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2
cn.hutool
hutool-all
5.4.5
org.apache.commons
commons-lang3
3.8.1
org.apache.poi
poi-ooxml
5.0.0
org.apache.poi
poi
5.0.0
org.springframework.boot
spring-boot-starter-data-redis
org.redisson
redisson
3.8.2
2、配置redisson
package com.lezu.springboot.configuration;
import org.redisson.Redisson;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(factory);
// key采用String的序列化方式
template.setKeySerializer(new StringRedisSerializer());
// hash的key也采用String的序列化方式
template.setHashKeySerializer(new StringRedisSerializer());
// value序列化方式采用jackson
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// hash的value序列化方式采用jackson
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
@Bean
public Redisson redisson() {
//单机模式
Config config = new Config();
config.useSingleServer()
.setAddress("redis://127.0.0.1:6379")
.setDatabase(0);
return (Redisson) Redisson.create(config);
}
// 主从
// Config config = new Config();
// config.useMasterSlaveServers()
// .setMasterAddress("127.0.0.1:6379")
// .addSlaveAddress("127.0.0.1:6389", "127.0.0.1:6332", "127.0.0.1:6419")
// .addSlaveAddress("127.0.0.1:6399");
// RedissonClient redisson = Redisson.create(config);
//
//
//哨兵
// Config config = new Config();
// config.useSentinelServers()
// .setMasterName("mymaster")
// .addSentinelAddress("127.0.0.1:26389", "127.0.0.1:26379")
// .addSentinelAddress("127.0.0.1:26319");
// RedissonClient redisson = Redisson.create(config);
//
//
//集群
// Config config = new Config();
// config.useClusterServers()
// .setScanInterval(2000) // cluster state scan interval in milliseconds
// .addNodeAddress("127.0.0.1:7000", "127.0.0.1:7001")
// .addNodeAddress("127.0.0.1:7002");
// RedissonClient redisson = Redisson.create(config);
}
3、redis分布式锁工具类
package com.lezu.springboot.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class RedisLock {
@Autowired
private RedisTemplate redisTemplate;
private ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 10, 10,
TimeUnit.SECONDS, new LinkedBlockingDeque<>(100));
public boolean lock(String key, String userId, long timeOut) {
boolean success = redisTemplate.opsForValue().setIfAbsent(key, userId, timeOut, TimeUnit.SECONDS);
if (!success) {
log.error("key:{},userId:{} get lock failer ", key, userId);
return false;
}
try {
renewExpiration(key, userId, timeOut);
TimeUnit.SECONDS.sleep(2);
return true;
} catch (Exception e) {
log.error("lock occur error:{}", e);
return false;
} finally {
releaseLock(key, userId);
}
}
private void renewExpiration(String key, String userId, long timeOut) {
threadPool.execute(() -> {
Long currentTimeMills = System.currentTimeMillis();
System.out.println("开始:" + LocalDateTime.now() + " ,timeOut:" + timeOut);
while (true) {
if (redisTemplate.hasKey(key) && userId.equals(redisTemplate.opsForValue().get(key))) {
Long cost = System.currentTimeMillis() - currentTimeMills;
if (cost > timeOut * 1000 / 2) {
currentTimeMills = System.currentTimeMillis();
redisTemplate.expire(key, timeOut, TimeUnit.SECONDS);
System.out.println("进行中:" + LocalDateTime.now() + " ,timeOut:" + timeOut);
}
} else {
break;
}
}
});
}
public void releaseLock(String key, String userId) {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
DefaultRedisScript redisScript = new DefaultRedisScript(script, Long.class);
Long result2 = redisTemplate.execute(redisScript, Arrays.asList(key), userId);
System.out.println("result2=" + result2);
}
}
4、实际使用操作
package com.lezu.springboot.controller;
import com.lezu.springboot.utils.RedisLockUtil;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@RestController
public class RedisController {
@Autowired
private RedisLockUtil releaseLock;
@Autowired
private Redisson redisson;
@Autowired
private StringRedisTemplate redisTemplate;
private Lock lock = new ReentrantLock();
@RequestMapping("/deductStock1")
public String deductStock1() throws InterruptedException {
//商品数量
// int stock = Integer.parseInt(redisTemplate.opsForValue().get("stock"));
// if (stock > 0) {
// int resultStock = stock - 1;
// redisTemplate.opsForValue().set("stock", resultStock + "");
// System.out.println("扣减成功,剩余库存:" + resultStock);
// } else {
// System.out.println("扣减失败,库存不足!");
// }
synchronized (this) {
int stock = Integer.parseInt(redisTemplate.opsForValue().get("stock"));
if (stock > 0) {
int resultStock = stock - 1;
redisTemplate.opsForValue().set("stock", resultStock + "");
System.out.println("扣减成功,剩余库存:" + resultStock);
} else {
System.out.println("扣减失败,库存不足!");
}
}
// lock.lock();
// try {
// int stock = Integer.parseInt(redisTemplate.opsForValue().get("stock"));
// if (stock > 0) {
// int resultStock = stock - 1;
// redisTemplate.opsForValue().set("stock", resultStock + "");
// System.out.println("扣减成功,剩余库存:" + resultStock);
// } else {
// System.out.println("扣减失败,库存不足!");
// }
// } catch (Exception e) {
// e.printStackTrace();
// return "error";
// } finally {
// lock.unlock();
// }
return "success";
}
@RequestMapping("/deductStock2")
public String deductStock2() {
String lockKey = "product_001"; //商品ID(前端传入)
try {
Boolean result = redisTemplate.opsForValue().setIfAbsent("product_001", "userId");
//代码突然报错导致设置超时时间这段代码没走
redisTemplate.expire(lockKey, 10, TimeUnit.SECONDS);
// Boolean result = redisTemplate.opsForValue().setIfAbsent(lockKey, "lock",10, TimeUnit.SECONDS);
//加锁失败直接返回error
if (!result) {
return "error";
}
//执行业务代码...
int stock = Integer.parseInt(redisTemplate.opsForValue().get("stock"));
if (stock > 0) {
int resultStock = stock - 1;
redisTemplate.opsForValue().set("stock", resultStock + "");
System.out.println("扣减成功,剩余库存:" + resultStock);
} else {
System.out.println("扣减失败,库存不足!");
}
} catch (Exception e) {
e.printStackTrace();
return "error";
} finally {
//删除key释放锁
redisTemplate.delete(lockKey);
}
return "success";
}
@RequestMapping("/deductStock3")
public String deductStock3() {
String lockKey = "product_001"; //商品ID(前端传入)
try {
//加锁
boolean lock = releaseLock.lock(lockKey, "userId", 10);
if (!lock) {
return "error";
}
//执行业务代码...
int stock = Integer.parseInt(redisTemplate.opsForValue().get("stock"));
if (stock > 0) {
int resultStock = stock - 1;
redisTemplate.opsForValue().set("stock", resultStock + "");
System.out.println("扣减成功,剩余库存:" + resultStock);
} else {
System.out.println("扣减失败,库存不足!");
}
} catch (Exception e) {
e.printStackTrace();
return "error";
} finally {
//释放锁
releaseLock.releaseLock(lockKey, "userId");
}
return "success";
}
@RequestMapping("/deductStock4")
public String deductStock4() {
String lockKey = "product_001"; //商品ID(前端传入)
RLock redissonLock = redisson.getLock(lockKey);
try {
//加锁(启动看门狗机制)
redissonLock.lock();
//redissonLock.lock(30, TimeUnit.SECONDS);
//执行业务代码...
int stock = Integer.parseInt(redisTemplate.opsForValue().get("stock"));
if (stock > 0) {
int resultStock = stock - 1;
redisTemplate.opsForValue().set("stock", resultStock + "");
System.out.println("扣减成功,剩余库存:" + resultStock);
} else {
System.out.println("扣减失败,库存不足!");
}
} catch (Exception e) {
e.printStackTrace();
return "error";
} finally {
//释放锁
redissonLock.unlock();
}
return "success";
}
}