代码实现

package com.by;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@SpringBootTest
class SetnxDemoTest {

    @Resource(name="redisTemplate")
    private ValueOperations valueOperations;

    private final  String key = "product#01";

    /**
     * redis 分布式锁 setnx
     */
    @Test
    void test() {
        //开启一个线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i=0;i<10;i++){
          //execute执行
           executorService.execute(()->{
               //如果不存在设置这个key
               Boolean b = valueOperations.setIfAbsent(key, "2022622-1w");
               if(b){
                   System.out.println(StrUtil.format("线程{}获取分布式锁成功",Thread.currentThread().getName()));
               }else {
                   System.out.println(StrUtil.format("线程{}获取分布式锁失败",Thread.currentThread().getName()));
               }
           });
        }
        ThreadUtil.safeSleep(10*1000);
}}

运行结果
在这里插入图片描述

Logo

更多推荐