定时测试类:
pom 依赖:
<!--使用redisson作为分布式锁-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.16.8</version>
</dependency>
@Scheduled(cron = "0/40 * * * * ?")
public void publishXXInfoUnloadingOil(){
ThreadPoolTaskExecutor threadPoolTaskExecutor = SpringUtils.getBean("threadPoolTaskExecutor");
for (int i = 0; i < 10; i++) {
AtomicInteger atomicInteger = new AtomicInteger(i);
RLock myLock = redissonClient.getLock("myLock");
myLock.lock();
try {
// 1、锁的自动续期,运行期间自动给锁续上新的30s,无需担心业务时间长,锁过期会自动被释放
// 2、加锁的业务只要运行完成,就不会给当前锁续期,即使不手动释放锁,锁默认在30s后自动释放,避免死锁
threadPoolTaskExecutor.execute(new Runnable() {
@Override
public void run() {
fuelDeviceService.test(atomicInteger.intValue());
}
});
// if(i == 1){
// Thread.sleep(40000);
// }
System.out.println("加锁成功,执行业务代码..."+Thread.currentThread().getId());
} catch (Exception e) {
e.printStackTrace();
}finally {
System.out.println("释放锁..."+Thread.currentThread().getId());
myLock.unlock();
}
System.out.println("成功:" + i);
}
System.out.println("结束");
}
接口:
public String test(int size);
实现类:
public String test(int size){
String stock1 = redis.getCacheObject("stock");
int stock = Integer.parseInt(stock1);
// 如果库存数量大于0
if (stock > 0) {
Random random = new Random();
int bugCount = random.nextInt(20) + 1;
if(stock < bugCount){
System.out.println(size + "序号:" + Thread.currentThread().getName() + "库存只有" + stock + ",您需要购买" + bugCount + ",库存不足!");
}else {
int realStock = stock - bugCount;
redis.setCacheObject("stock", realStock + "");
System.out.println(size + "序号:" + Thread.currentThread().getName() + "扣减成功, 购买了",剩余库存:" + realStock + "");
}
} else { // 如果库存数量小于0
System.out.println(size + "序号:" + Thread.currentThread().getName() + "扣减失败,库存" + stock + ",库存不足!");
}
return "end";
}
配置类:
package com.fuel.common.config;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyRedissonConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private String port;
@Value("${spring.redis.password}")
private String password;
/**
* 所有对Redisson的使用都是通过RedissonClient对象
* @return
*/
@Bean(destroyMethod = "shutdown")
public RedissonClient redissonClient(){
// 创建配置 指定redis地址及节点信息
Config config = new Config();
config.useSingleServer().setAddress("redis://" + host + ":" + port).setPassword(password);
// 根据config创建出RedissonClient实例
RedissonClient redissonClient = Redisson.create(config);
return redissonClient;
}
}