Search in sources :

Example 1 with StockCache

use of com.whoiszxl.cqrs.cache.StockCache in project shopzz by whoiszxl.

the class DefaultStockCacheServiceImpl method getAvailableStock.

@Override
public StockCache getAvailableStock(Long itemId) {
    // 从本地缓存中获取到item的库存
    StockCache stockCache = stockCacheCache.getIfPresent(itemId);
    if (stockCache != null) {
        return stockCache;
    }
    // 如果不存在,则从redis中获取
    Object stockQuantityObj = redisUtils.getObj(RedisKeyPrefixConstants.CACHE_ITEM_STOCK + itemId);
    if (stockQuantityObj == null) {
        return null;
    }
    Integer stockQuantity = Integer.parseInt(stockQuantityObj.toString());
    stockCache = new StockCache().with(stockQuantity);
    return stockCache;
}
Also used : StockCache(com.whoiszxl.cqrs.cache.StockCache)

Example 2 with StockCache

use of com.whoiszxl.cqrs.cache.StockCache in project shopzz by whoiszxl.

the class QueuedPlaceOrderServiceImpl method refreshLatestAvailableToken.

/**
 * 从库存里获取可用token数量
 * token数量默认是库存的1.5倍,适量放行一些请求进来争抢资源
 * @param seckillItemId
 * @return
 */
private Integer refreshLatestAvailableToken(Long seckillItemId) {
    DistributedLock distributedLock = distributedLockFactory.getDistributedLock(RedisKeyPrefixConstants.LOCK_SECKILL_REFRESH_PLACE_ORDER_TOKEN + seckillItemId);
    try {
        boolean lockFlag = distributedLock.tryLock(500, 1000, TimeUnit.MILLISECONDS);
        if (!lockFlag) {
            return null;
        }
        StockCache stockCache = stockCacheService.getAvailableStock(seckillItemId);
        if (stockCache != null && stockCache.isSuccess() && stockCache.getAvailableStockQuantity() != null) {
            Integer latestAvailableOrderToken = (int) Math.ceil(stockCache.getAvailableStockQuantity() * 1.5);
            redisUtils.setEx(RedisKeyPrefixConstants.TOKEN_SECKILL_PLACE_ORDER + seckillItemId, latestAvailableOrderToken.toString(), 24, TimeUnit.HOURS);
            availableOrderTokenLocalCache.put(seckillItemId, latestAvailableOrderToken);
            return latestAvailableOrderToken;
        }
    } catch (Exception e) {
        log.error("refreshLatestAvailableToken|刷新最新可用令牌失败|{}", seckillItemId, e);
    } finally {
        distributedLock.unlock();
    }
    return null;
}
Also used : DistributedLock(com.whoiszxl.DistributedLock) StockCache(com.whoiszxl.cqrs.cache.StockCache)

Aggregations

StockCache (com.whoiszxl.cqrs.cache.StockCache)2 DistributedLock (com.whoiszxl.DistributedLock)1