事务面试

`spring boot`高并发秒杀测试

2018-06-26  本文已影响893人  wine_5664

redis高并发秒杀测试

测试项目: https://github.com/14251104246/redis-demo.git

准备

重现秒杀时出现的超卖问题

/**
 * 用于测试redis秒杀
 */
@RestController
@RequestMapping("/api/spike")
@Slf4j
public class SpikeController {

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;
    
    //记录实际卖出的商品数量
    private AtomicInteger successNum = new AtomicInteger(0);

    @RequestMapping(value = "/initSku", method = RequestMethod.GET)
    public String initSku() {
        //初始化库存数量
        stringRedisTemplate.opsForValue().set("product_sku", "5");
        //初始化实际卖出的商品数量0
        successNum.set(0);
        return "初始化库存成功";
    }

    /**
     * 会出现超卖情况的减少库存方式
     * @return
     */
    @RequestMapping(value = "/reduceSku", method = RequestMethod.GET)
    public String reduceSku() {
        Integer sku = Integer.parseInt(stringRedisTemplate.opsForValue().get("product_sku"));
        sku = sku - 1;
        if (sku < 0) {
            return "库存不足";
        }

        stringRedisTemplate.opsForValue().set("product_sku", sku.toString());
        //记录实际卖出的商品数量
        return "减少库存成功,共减少" + successNum.incrementAndGet();
    }

    @RequestMapping(value = "/successNum", method = RequestMethod.GET)
    public String successNum() {
        return "顾客成功抢到的商品数量:" + successNum.get();
    }
}
API{初始化库存数量} >> http://127.0.0.1:8090/api/spike/initSku
API{减少库存数量} >> http://127.0.0.1:8090/api/spike/reduceSku
API{查看共减少库存数量} >> http://127.0.0.1:8090/api/spike/successNum

超卖问题原因分析

/**
 * 会出现超卖情况的减少库存方式
 * @return
 */
@RequestMapping(value = "/reduceSku", method = RequestMethod.GET)
public String reduceSku() {
    Integer sku = Integer.parseInt(stringRedisTemplate.opsForValue().get("product_sku"));
    sku = sku - 1;
    if (sku < 0) {
        return "库存不足";
    }

    stringRedisTemplate.opsForValue().set("product_sku", sku.toString());
    //记录实际卖出的商品数量
    return "减少库存成功,共减少" + successNum.incrementAndGet();
}

通过redis事务解决超卖问题

使用redis原生的sdk
    /**
     * 加入事务的减少库存方式
     * @return
     */
    @RequestMapping(value = "/reduceSku3", method = RequestMethod.GET)
    public String reduceSku3() {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        List<Object> result ;
        Transaction transaction = null;
        try {
            jedis.watch("product_sku");
            int sku = Integer.parseInt(jedis.get("product_sku"));
            if (sku > 0) {
                transaction = jedis.multi();
                transaction.set("product_sku", String.valueOf(sku - 1));
//                int exp = 1/0;
                result = transaction.exec();
                if (result == null || result.isEmpty()) {
                    System.out.println("Transaction error...");// 可能是watch-key被外部修改,或者是数据操作被驳回
//                    transaction.discard();  //watch-key被外部修改时,discard操作会被自动触发
                    return "Transaction error...";
                }
            } else {
                return "库存不足";
            }
            return "减少库存成功,共减少" + successNum.incrementAndGet();
        } catch (Exception e) {
            log.error(e.getMessage());
            transaction.discard();
            return "fail";
        }
    }
spring的redisTemplate执行事务
@RequestMapping(value = "/reduceSku2", method = RequestMethod.GET)
public String reduceSku2() {
    stringRedisTemplate.setEnableTransactionSupport(true);
    List<Object> results = stringRedisTemplate.execute(new SessionCallback<List<Object>>() {
        @Override
        public List<Object> execute(RedisOperations operations) throws DataAccessException {
            operations.watch("product_sku");
            String product_sku = (String) operations.opsForValue().get("product_sku");
            operations.multi();
            operations.opsForValue().get("product_sku");//必要的空查询
            Integer sku = Integer.parseInt(product_sku);
            sku = sku - 1;
            if (sku < 0) {
                return null;
            }
            operations.opsForValue().set("product_sku", sku.toString());
            return operations.exec();
//                operations.unwatch(); //执行exec()后自动unwatch()

        }
    });

    if (results != null && results.size() > 0) {
        return "减少库存成功,共减少" + successNum.incrementAndGet();
    }

    return "库存不足";
//        return result.toString();
}
spring的redisTemplate执行事务(使用zset
@RequestMapping(value = "/reduceSku", method = RequestMethod.GET)
public String reduceSku5(String pid) {
    pid = pid==null? String.valueOf(1) :pid;
    String finalPid = pid;
    List<Object> results = redisTemplate.execute(new SessionCallback<List<Object>>() {
        @Override
        public List<Object> execute(RedisOperations redisOperations) throws DataAccessException {
            String key = "product";
            redisOperations.watch(key);
            ZSetOperations<String, String> kvzSetOperations = redisOperations.opsForZSet();
            Object score = kvzSetOperations.score(key, finalPid);
            redisOperations.multi();
            if (score != null && Double.valueOf(score.toString()) > 0) {
                kvzSetOperations.incrementScore("product", finalPid, -1);
            }
            return redisOperations.exec();

        }
    });

    if (results != null && results.size() > 0) {
        return "减少库存成功,共减少" + successNum.incrementAndGet();
    }

    return "库存不足";
}

通过加锁方式解决超卖问题

@RequestMapping(value = "/reduceSku4", method = RequestMethod.GET)
public String reduceSku4() {
    RLock rLock = redissonClient.getLock("product_sku");
    try {
        rLock.lock();

        Integer sku = Integer.parseInt(stringRedisTemplate.opsForValue().get("product_sku"));
        sku = sku - 1;
        if (sku < 0) {
            return "库存不足";
        }

        stringRedisTemplate.opsForValue().set("product_sku", sku.toString());

        return "减少库存成功,共减少" + successNum.incrementAndGet();
    } finally {
        rLock.unlock();
    }

}
上一篇下一篇

猜你喜欢

热点阅读