redis扣减库存示例代码 java

使用redis扣减库存,保证库存不超发或少发的核心是保证redis读取库存和扣减库存的原子性。不能多个线程读取同一时刻的库存再去做扣减,也不能多个线程先扣减库存再去读库存。

下面先介绍正确实例

1.使用lua脚本

SpringDataRedis版本 代码如下

package com.wl.redis.jedis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by wl on 2021/6/16.
 */
@Component
public class RedisStock implements InitializingBean{

    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    public RedisStock(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public boolean decrementStockWithLuaRedisTemplate(){
        String script = "local stock = redis.call('get',KEYS[1]); local decrementNumber = tonumber(ARGV[1]);" +
                " if tonumber(stock) + decrementNumber >= 0 then redis.call('INCRBY',KEYS[1],decrementNumber) return 1;" +
                " end return 0;";

        List<String> keys = new ArrayList<>();
        RedisScript redisScript = new DefaultRedisScript<>(script,Long.class);
        keys.add("stock");
        //-1表示decrementNumber  根据自己的扣减库存量自行设置
        Object[] args = {"-1"};
        Long result =  (Long) stringRedisTemplate.execute(redisScript,keys,args);
        return result == 1L;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        stringRedisTemplate.opsForValue().set("stock", "100");
    }
}

测试代码如下(开启六个线程调用扣减库存的方法)

package com.wl.redis;

import com.wl.redis.jedis.RedisStock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by wl on 2021/6/16.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class RedisStockTest {

    @Autowired
    private RedisStock redisStock;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private AtomicInteger count = new AtomicInteger(0);


    @Test
    public void testDecrementStockWithLuaRedisTemplate() throws Exception{
        CountDownLatch countDownLatch = new CountDownLatch(6);
        List<Thread> list = new ArrayList<>();
        for (int i=0;i<6;i++){
            list.add(new Thread(() -> {
                while (true){
                    if(!redisStock.decrementStockWithLuaRedisTemplate()){
                        countDownLatch.countDown();
                        break;
                    }else{
                        count.addAndGet(1);
                    }
                }
            }));
        }
        for(int i=0;i<6;i++){
            list.get(i).start();
        }
        countDownLatch.await();
        System.out.println("扣减库存返回true的次数:" + count.get());
        System.out.println("剩余库存数量:" + stringRedisTemplate.opsForValue().get("stock"));

    }

    


}

执行结果如下(执行耗时2秒)

2021-06-16 23:25:31.632  INFO 14764 --- [           main] com.wl.redis.RedisStockTest              : Started RedisStockTest in 11.023 seconds (JVM running for 12.999)
扣减库存返回true的次数:100
剩余库存数量:0

Jedis版本代码

    private JedisPool pool = new JedisPool(new GenericObjectPoolConfig(),"localhost",6379,3000,"password",0);

    public boolean decrementStockWithLuaJedis(){
        String script = "local stock = redis.call('get',KEYS[1]); local decrementNumber = tonumber(ARGV[1]);" +
                " if tonumber(stock) + decrementNumber >= 0 then redis.call('INCRBY',KEYS[1],decrementNumber) return 1;" +
                " end return 0;";
        List<String> keys = new ArrayList<>();
        keys.add("stock");
        //-1表示decrementNumber  根据自己的扣减库存量自行设置
        String[] args = {"-1"};
        Jedis jedis = pool.getResource();
        try {
            Long result = (Long) jedis.eval(script, keys, Arrays.asList(args));
            return result == 1L;
        }catch (Exception e){
            //
        }finally {
            jedis.close();
        }
        return false;
    }

测试代码

    @Test
    public void testDecrementStockWithLuaJedis() throws Exception{
        CountDownLatch countDownLatch = new CountDownLatch(6);
        List<Thread> list = new ArrayList<>();
        for (int i=0;i<6;i++){
            list.add(new Thread(() -> {
                while (true){
                    if(!redisStock.decrementStockWithLuaJedis()){
                        countDownLatch.countDown();
                        break;
                    }else{
                        count.addAndGet(1);
                    }
            
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值