package com.test;
import java.util.concurrent.TimeUnit;
import org.apache.tomcat.jni.Lock;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.config.Config;
import org.redisson.spring.starter.RedissonAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import cn.hutool.core.lang.UUID;
public class test3 {
@Bean
private Redisson redisson() {
Config config = new Config();
config.useSingleServer().setAddress("").setDatabase(0);
return (Redisson) Redisson.create(config);
}
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private Redisson redisson;
String everKey = "code01";
public String method() {
String code = UUID.randomUUID().toString();
RLock lock = redisson.getLock(everKey);
try {
Boolean setIfAbsent = stringRedisTemplate.opsForValue().setIfAbsent(everKey, code);
stringRedisTemplate.expire(everKey, 5, TimeUnit.SECONDS);
if (!setIfAbsent) {
return "error";
}
lock.lock(10, TimeUnit.SECONDS);
int i = Integer.parseInt(stringRedisTemplate.opsForValue().get("count"));
if (i > 0) {
stringRedisTemplate.opsForValue().set("count", (i--) + "");
System.out.println("成功");
} else {
System.out.println("失败");
}
} finally {
lock.unlock();
if (code.equals(stringRedisTemplate.opsForValue().get(everKey)))
stringRedisTemplate.delete(everKey);
}
return code;
}
}
redis实现分布式锁代码展示
最新推荐文章于 2024-09-12 08:00:00 发布