目录
1.目的
redis实现分布式锁,进行加锁获取
2.实现
1.配置redis
2.代码
package com.alspd.wx.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
/**
* 类描述: redis测试
*
* @author zhang pan
* @version 1.0
* @date 2023/4/11 11:37
*/
@Slf4j
@RestController
@RequestMapping("/redis")
public class RedisController {
@Autowired
StringRedisTemplate stringRedisTemplate;
@GetMapping("lock")
public String lock() {
toLock();
return "lock";
}
/**
* 获取锁并执行业务
*/
private void toLock() {
//等价于 setExNx 自动过期时间且不存在时插入
boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", "1", 10, TimeUnit.SECONDS);
if (lock) {
//执行业务
doBusiness();
stringRedisTemplate.delete("lock"); //此处扩展,解锁时也要保证原子性
} else {
toLock(); //获取不到锁时,自旋
}
}
private void doBusiness() {
// TODO: 2023/4/11 执行业务
log.info("doBusiness");
}
}
3.总结
此处只是一个简单的实现思路,需要继续扩展使用