阅读更多
redis之计数器:自增、自减
incr key: 将key中储存的数字值增1,并返回值
decr key: 将key中储存的数字值减1,并返回值
set num 1
incr num
@Controller("user_controller")
@RequestMapping("/user")
public class UserController{
@Autowired
private RedisService redisService;
private ReentrantLock lock = new ReentrantLock();
@RequestMapping("/")
public String list(Model model,HttpServletResponse response) {
lock.lock();
Long total = Long.valueOf(redisService.get("total"));
System.out.println("num="+num+",total="+total);
if(num<=total) {
Long num = redisService.incr("product.num");
}else{
System.out.println("num over!");
}
lock.unlock();
return "index";
}
}
@Service
public class RedisService {
@Autowired
private JedisPool jedisPool;
public Long incr(String key) {
Jedis j=null;
try{
j=jedisPool.getResource();
return j.incr(key);
}finally{
j.close();
}
}
public String get(String key) {
Jedis j=null;
try{
j=jedisPool.getResource();
return j.get(key);
}finally{
j.close();
}
}
}