赞
踩
作者:goodlook0123
https://blog.csdn.net/goodlook0123
面试常常遇到写一个抢购实例,或者讲讲抢购实现想法,然后总是讲不明白,因为目前工作没做抢购这一块儿。
但是这个想法今天终于搞明白了,其中也参照了一些大佬的做法。
这篇文章直接使用redis,其中注释也写的挺明白的,直接上代码:
junit测试类:
- Log log = LogFactory.getLog(getClass());
-
- @Autowired
- private RedisTemplate<String, Object> redisTemplate;
-
- @Test
- public void testSys() throws Exception{
- log.info("开始");
-
- MsService service = new MsService();
-
- for (int i = 0; i < 10; i++) {
- ThreadB threadA = new ThreadB(service, redisTemplate, "MSKEY");
- threadA.start();
- log.info("*******************结束");
- }
-
- }
threadB类:
- private MsService service;
- private RedisTemplate<String,Object> redisTemplate;
- private String key;
-
- public ThreadB(MsService service,RedisTemplate<String,Object> redisTemplate,String key) {
- this.service = service;
- this.redisTemplate=redisTemplate;
- this.key=key;
- }
-
- @Override
- public void run() {
- try {
- service.seckill(redisTemplate, key);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
msService类:
- Log log = LogFactory.getLog(getClass());
-
- /***
- * 抢购代码
- * @param redisTemplate
- * @param key pronum 首先用客户端设置数量
- * @return
- * @throws InterruptedException
- */
- public boolean seckill(RedisTemplate<String,Object> redisTemplate, String key) throws Exception {
- RedisLock lock = new RedisLock(redisTemplate, key, 10000, 20000);
- try {
- if (lock.lock()) {
- // 需要加锁的代码
- String pronum=lock.get("pronum");
- //修改库存
- if(Integer.parseInt(pronum)-1>=0) {
- lock.set("pronum",String.valueOf(Integer.parseInt(pronum)-1));
- log.info("库存数量:"+pronum+" 成功!!!"+Thread.currentThread().getName());
- }else {
- log.info("已经被抢光了,请参与下轮抢购");
- }
- log.info("++++++++++++++++++++++++++++++++++++++参加了抢购");
- return true;
- }
-
-
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- // 为了让分布式锁的算法更稳键些,持有锁的客户端在解锁之前应该再检查一次自己的锁是否已经超时,再去做DEL操作,因为可能客户端因为某个耗时的操作而挂起,
- // 操作完的时候锁因为超时已经被别人获得,这时就不必解锁了。 ————这里没有做
- lock.unlock();
- }
- return false;
- }
redisLock类:
- public class RedisLock {
-
- private static Logger logger = LoggerFactory.getLogger(RedisLock.class);
-
- private RedisTemplate<String,Object> redisTemplate;
-
- private static final int DEFAULT_ACQUIRY_RESOLUTION_MILLIS = 100;
-
- /**
- * Lock key path.
- */
- private String lockKey;
-
- /**
- * 锁超时时间,防止线程在入锁以后,无限的执行等待
- */
- private int expireMsecs = 60 * 1000;
-
- /**
- * 锁等待时间,防止线程饥饿
- */
- private int timeoutMsecs = 10 * 1000;
-
- private volatile boolean locked = false;
-
- /**
- * Detailed constructor with default acquire timeout 10000 msecs and lock
- * expiration of 60000 msecs.
- *
- * @param lockKey
- * lock key (ex. account:1, ...)
- */
- public RedisLock(RedisTemplate<String,Object> redisTemplate, String lockKey) {
- this.redisTemplate = redisTemplate;
- this.lockKey = lockKey + "_lock";
- }
-
- /**
- * Detailed constructor with default lock expiration of 60000 msecs.
- *
- */
- public RedisLock(RedisTemplate<String,Object> redisTemplate, String lockKey, int timeoutMsecs) {
- this(redisTemplate, lockKey);
- this.timeoutMsecs = timeoutMsecs;
- }
-
- /**
- * Detailed constructor.
- *
- */
- public RedisLock(RedisTemplate<String,Object> redisTemplate, String lockKey, int timeoutMsecs, int expireMsecs) {
- this(redisTemplate, lockKey, timeoutMsecs);
- this.expireMsecs = expireMsecs;
- }
-
- /**
- * @return lock key
- */
- public String getLockKey() {
- return lockKey;
- }
-
- public String get(final String key) {
- Object obj = null;
- try {
- obj = redisTemplate.execute(new RedisCallback<Object>() {
- @Override
- public Object doInRedis(RedisConnection connection) throws DataAccessException {
- StringRedisSerializer serializer = new StringRedisSerializer();
- byte[] data = connection.get(serializer.serialize(key));
- connection.close();
- if (data == null) {
- return null;
- }
- return serializer.deserialize(data);
- }
- });
- } catch (Exception e) {
- logger.error("get redis error, key : {}", key);
- }
- return obj != null ? obj.toString() : null;
- }
-
-
- public String set(final String key,final String value) {
- Object obj = null;
- try {
- obj = redisTemplate.execute(new RedisCallback<Object>() {
- @Override
- public Object doInRedis(RedisConnection connection) throws DataAccessException {
- StringRedisSerializer serializer = new StringRedisSerializer();
- connection.set(serializer.serialize(key), serializer.serialize(value));
- return serializer;
- }
- });
- } catch (Exception e) {
- logger.error("get redis error, key : {}", key);
- }
- return obj != null ? obj.toString() : null;
- }
-
- public boolean setNX(final String key, final String value) {
- Object obj = null;
- try {
- obj = redisTemplate.execute(new RedisCallback<Object>() {
- @Override
- public Object doInRedis(RedisConnection connection) throws DataAccessException {
- StringRedisSerializer serializer = new StringRedisSerializer();
- Boolean success = connection.setNX(serializer.serialize(key), serializer.serialize(value));
- connection.close();
- return success;
- }
- });
- } catch (Exception e) {
- logger.error("setNX redis error, key : {}", key);
- }
- return obj != null ? (Boolean) obj : false;
- }
-
- private String getSet(final String key, final String value) {
- Object obj = null;
- try {
- obj = redisTemplate.execute(new RedisCallback<Object>() {
- @Override
- public Object doInRedis(RedisConnection connection) throws DataAccessException {
- StringRedisSerializer serializer = new StringRedisSerializer();
- byte[] ret = connection.getSet(serializer.serialize(key), serializer.serialize(value));
- connection.close();
- return serializer.deserialize(ret);
- }
- });
- } catch (Exception e) {
- logger.error("setNX redis error, key : {}", key);
- }
- return obj != null ? (String) obj : null;
- }
-
- /**
- * 获得 lock. 实现思路: 主要是使用了redis 的setnx命令,缓存了锁. reids缓存的key是锁的key,所有的共享,
- * value是锁的到期时间(注意:这里把过期时间放在value了,没有时间上设置其超时时间) 执行过程:
- * 1.通过setnx尝试设置某个key的值,成功(当前没有这个锁)则返回,成功获得锁
- * 2.锁已经存在则获取锁的到期时间,和当前时间比较,超时的话,则设置新的值
- *
- * @return true if lock is acquired, false acquire timeouted
- * @throws InterruptedException
- * in case of thread interruption
- */
- public synchronized boolean lock() throws InterruptedException {
- int timeout = timeoutMsecs;
- while (timeout >= 0) {
- long expires = System.currentTimeMillis() + expireMsecs + 1;
- String expiresStr = String.valueOf(expires); // 锁到期时间
- if (this.setNX(lockKey, expiresStr)) {
- // lock acquired
- locked = true;
- return true;
- }
-
- String currentValueStr = this.get(lockKey); // redis里的时间
- if (currentValueStr != null && Long.parseLong(currentValueStr) < System.currentTimeMillis()) {
- // 判断是否为空,不为空的情况下,如果被其他线程设置了值,则第二个条件判断是过不去的
- // lock is expired
-
- String oldValueStr = this.getSet(lockKey, expiresStr);
- // 获取上一个锁到期时间,并设置现在的锁到期时间,
- // 只有一个线程才能获取上一个线上的设置时间,因为jedis.getSet是同步的
- if (oldValueStr != null && oldValueStr.equals(currentValueStr)) {
- // 防止误删(覆盖,因为key是相同的)了他人的锁——这里达不到效果,这里值会被覆盖,但是因为什么相差了很少的时间,所以可以接受
-
- // [分布式的情况下]:如过这个时候,多个线程恰好都到了这里,但是只有一个线程的设置值和当前值相同,他才有权利获取锁
- // lock acquired
- locked = true;
- return true;
- }
- }
- timeout -= DEFAULT_ACQUIRY_RESOLUTION_MILLIS;
-
- /*
- * 延迟100 毫秒, 这里使用随机时间可能会好一点,可以防止饥饿进程的出现,即,当同时到达多个进程,
- * 只会有一个进程获得锁,其他的都用同样的频率进行尝试,后面有来了一些进行,也以同样的频率申请锁,这将可能导致前面来的锁得不到满足.
- * 使用随机的等待时间可以一定程度上保证公平性
- */
- Thread.sleep(DEFAULT_ACQUIRY_RESOLUTION_MILLIS);
-
- }
- return false;
- }
-
- /**
- * Acqurired lock release.
- */
- public synchronized void unlock() {
- if (locked) {
- redisTemplate.delete(lockKey);
- locked = false;
- }
- }
至此基于redis的抢购简单实现。大佬如果觉得有不妥的地方请指正,小弟也可以进步一点点。
Java面试题专栏
【71期】面试官:对并发熟悉吗?谈谈你对Java中常用的几种线程池的理解
【72期】面试官:对并发熟悉吗?说一下synchronized与Lock的区别与使用
【73期】面试官:Spring 和 Spring Boot 的区别是什么?
【75期】面试官:说说Redis的过期键删除策略吧!(高频)
【79期】别找了,回答Spring中Bean的生命周期,这里帮你总结好了!
欢迎长按下图关注公众号后端技术精选
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。