package com.example.testdocker.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@RestController
public class Tt {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@GetMapping("/buy")
public String buy() {
String lock = "lock";
String lock_value = UUID.randomUUID().toString();
Boolean isLock = redisTemplate.opsForValue().setIfAbsent(lock,lock_value);
if(! isLock){
return "购买失败";
}
// 设置超时时间,防止死锁
redisTemplate.expire("lock", 10, TimeUnit.SECONDS);
try {
Integer order = (Integer) redisTemplate.opsForValue().get("order");
if (order > 0) {
redisTemplate.opsForValue().set("order", order - 1);
System.out.println("购买成功" + order);
Integer bycount = (Integer) redisTemplate.opsForValue().get("bycount");
redisTemplate.opsForValue().set("bycount", bycount + 1);
return "购买成功";
} else {
System.out.println("库存不足");
return "库存不足";
}
}finally {
// 释放锁
if (lock_value.equals(redisTemplate.opsForValue().get(lock))){
redisTemplate.delete(lock);
}
}
}
// 为了查看当前库存,可以添加一个查询库存的接口
@GetMapping("/stock")
public String checkStock() {
return redisTemplate.opsForValue().get("order").toString()+" ==== "+
redisTemplate.opsForValue().get("bycount").toString();
}
@GetMapping("/setstock")
public String setCheckStock(Integer count) {
redisTemplate.opsForValue().set("order", count);
redisTemplate.opsForValue().set("bycount", 0);
return redisTemplate.opsForValue().get("order").toString();
}
}
springboot + redis 实现分布式锁
最新推荐文章于 2024-07-24 20:42:29 发布