<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
@RequestMapping("/m1")
public int insertUserT3() {
String lockKey="lockKey";
boolean ok= stringRedisTemplate.opsForValue().setIfAbsent("lockKey","m1");
try
{
if (!ok)
{
return -1;
}
num=num+1;
userServiceTest02.insertUser("m1",num );
}finally {
stringRedisTemplate.delete(lockKey);
}
return 1;
}
redisson 解决方案
Pom 的解决文件
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.11.1</version>
</dependency>
@Configuration
public class RedisConfig {
@Bean("redission")
public Redisson redissonClient() {
Config config = new Config();
// 单机模式
config.useSingleServer()
.setAddress("redis://127.0.0.1:6379").setDatabase(0);
return(Redisson)Redisson.create(config);
}
}
@Autowired
Redisson redisson;
@RequestMapping("/mm")
public int insertUserT2() {
String strKey="stockKey";
RLock Redissionlock= redisson.getLock(strKey);
try
{
Redissionlock.lock();
num=num+1;
userServiceTest02.insertUser("zhangsan",num );
}
finally {
Redissionlock.unlock();
}
return 1;
}
------------------------------------------------------------------------------------------------------------------------------------------------
检查数据是否有重复
DELETE FROM users;
SELECT * FROM users WHERE age=2;
SELECT * FROM users GROUP BY age HAVING COUNT(age)>1;