Просмотр исходного кода

setnx代码 服务单机测试 可以

dinglan 2 лет назад
Родитель
Сommit
4b8395bce3

+ 0 - 2
src/main/java/com/sw/controller/SnatchMaskController.java

@@ -53,8 +53,6 @@ public class SnatchMaskController {
             if (redisTemplate.opsForSet().isMember("successUserUids", uid)) {
                 return "你已经抢到口罩了";
             } else {
-                Object o = new Object();
-//                synchronized (o){
                     Boolean flag = snatchMaskService.checkAndDecrRemaining(mid);
                     if (flag) {
                         return snatchMaskService.doSnatchMQ(uid, mid);

+ 40 - 14
src/main/java/com/sw/service/impl/SnatchMaskServiceImpl.java

@@ -1,6 +1,5 @@
 package com.sw.service.impl;
 
-import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.sw.activemq.producer.IMessageProducerService;
 import com.sw.domain.TMask;
 import com.sw.service.SnatchMaskService;
@@ -11,17 +10,16 @@ import org.redisson.api.RLock;
 import org.redisson.api.RedissonClient;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
+import org.springframework.data.redis.connection.RedisConnection;
 import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
-import org.springframework.web.bind.annotation.RequestMapping;
 
 import javax.annotation.Resource;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.LockSupport;
 import java.util.concurrent.locks.ReentrantLock;
 
 /**
@@ -81,23 +79,51 @@ public class SnatchMaskServiceImpl implements SnatchMaskService {
      */
     @Override
     public Boolean checkAndDecrRemaining(Integer mid) {
-
-        reentrantLock.lock();
+        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
+        Boolean flag = false;
         try {
-            Integer remaining = Integer.valueOf(redisTemplate.opsForHash().get("usableMasks", "mask-" + mid).toString());
-            System.out.println("库存扣减前:" + remaining + "---" + Thread.currentThread());
-            if (remaining.compareTo(amount) >= 0) {
-                Long res = redisTemplate.opsForHash().increment("usableMasks", "mask-" + mid, -amount);
-                System.out.println("库存扣减后:" + "increment res : " + res + "---" + Thread.currentThread());//扣减之后的库存数量
-                return true;
-            } else {
-                return false;
+
+            while (!connection.setNX(redisTemplate.getKeySerializer().serialize("mask-setnx-mq"), redisTemplate.getValueSerializer().serialize(1))) {
+                Thread.sleep(3);
             }
+                Integer remaining = Integer.valueOf(redisTemplate.opsForHash().get("usableMasks", "mask-" + mid).toString());
+                System.out.println("库存扣减前:" + remaining + "---" + Thread.currentThread());
+                if (remaining.compareTo(amount) >= 0) {
+                    Long res = redisTemplate.opsForHash().increment("usableMasks", "mask-" + mid, -amount);
+                    System.out.println("库存扣减后:" + "increment res : " + res + "---" + Thread.currentThread());//扣减之后的库存数量
+                    flag = true;
+                } else {
+                    flag = false;
+                }
+
+            connection.close();
+            return flag;
+        } catch (InterruptedException e) {
+            e.printStackTrace();
         } finally {
-            reentrantLock.unlock();
+            connection.del(redisTemplate.getKeySerializer().serialize("mask-setnx-mq"));
+            connection.close();
+            return  flag;
         }
 
 
+
+//        reentrantLock.lock();
+//        try {
+//            Integer remaining = Integer.valueOf(redisTemplate.opsForHash().get("usableMasks", "mask-" + mid).toString());
+//            System.out.println("库存扣减前:" + remaining + "---" + Thread.currentThread());
+//            if (remaining.compareTo(amount) >= 0) {
+//                Long res = redisTemplate.opsForHash().increment("usableMasks", "mask-" + mid, -amount);
+//                System.out.println("库存扣减后:" + "increment res : " + res + "---" + Thread.currentThread());//扣减之后的库存数量
+//                return true;
+//            } else {
+//                return false;
+//            }
+//        } finally {
+//            reentrantLock.unlock();
+//        }
+
+
    /*     synchronized (o) {
 //            Integer  remaining = 0;
             Integer   remaining = Integer.valueOf(redisTemplate.opsForHash().get("usableMasks", "mask-" + mid).toString());

+ 22 - 21
src/test/java/com/sw/RedisTest.java

@@ -82,27 +82,28 @@ public class RedisTest {
         byte[] key = redisTemplate.getKeySerializer().serialize("mask-setnx-mq");
         byte[] value = redisTemplate.getValueSerializer().serialize(1);
 
-        Object nativeConnection = redisTemplate.getConnectionFactory().getConnection().getNativeConnection();
-        //lettuce连接下 redis单机setnx
-        if(nativeConnection instanceof RedisAsyncCommands){
-            RedisAsyncCommands commands = (RedisAsyncCommands) nativeConnection;
-            String res = commands.getStatefulConnection().sync()
-                    .set(key, value, SetArgs.Builder.nx().ex(10));
-            System.out.println(res);
-        }
-        if(nativeConnection instanceof RedissonClient){
-            RedisAsyncCommands commands = (RedisAsyncCommands) nativeConnection;
-            String res = commands.getStatefulConnection().sync()
-                    .set(key, value, SetArgs.Builder.nx().ex(10));
-            System.out.println(res);
-        }
-        //lettuce连接下 redis集群setnx
-        if(nativeConnection instanceof RedisAdvancedClusterAsyncCommands){
-            RedisAdvancedClusterAsyncCommands commands = (RedisAdvancedClusterAsyncCommands) nativeConnection;
-            String res = commands.getStatefulConnection().sync()
-                    .set(key, value, SetArgs.Builder.nx().ex(10));
-            System.out.println(res);
-        }
+        Boolean res = redisTemplate.getConnectionFactory().getConnection().setNX(key, value);
+        System.out.println(res);
+//        //lettuce连接下 redis单机setnx
+//        if(nativeConnection instanceof RedisAsyncCommands){
+//            RedisAsyncCommands commands = (RedisAsyncCommands) nativeConnection;
+//            String res = commands.getStatefulConnection().sync()
+//                    .set(key, value, SetArgs.Builder.nx().ex(10));
+//            System.out.println(res);
+//        }
+//        if(nativeConnection instanceof RedissonClient){
+//            RedisAsyncCommands commands = (RedisAsyncCommands) nativeConnection;
+//            String res = commands.getStatefulConnection().sync()
+//                    .set(key, value, SetArgs.Builder.nx().ex(10));
+//            System.out.println(res);
+//        }
+//        //lettuce连接下 redis集群setnx
+//        if(nativeConnection instanceof RedisAdvancedClusterAsyncCommands){
+//            RedisAdvancedClusterAsyncCommands commands = (RedisAdvancedClusterAsyncCommands) nativeConnection;
+//            String res = commands.getStatefulConnection().sync()
+//                    .set(key, value, SetArgs.Builder.nx().ex(10));
+//            System.out.println(res);
+//        }
 //        racac.getStatefulConnection().async().setnx("")
 //        redisTemplate.opsForValue().set("remain", 100);
     }