添加接口防抖

This commit is contained in:
韩鹏辉 2024-06-14 14:24:14 +08:00
parent 6ab2a32c9f
commit ada1dafe86
5 changed files with 305 additions and 285 deletions

View File

@ -0,0 +1,22 @@
package com.chaozhanggui.system.cashierservice.annotation;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface LimitSubmit {
String key() ;
/**
* 默认 10s
*/
int limit() default 30;
/**
* 请求完成后 是否一直等待
* true则等待
* @return
*/
boolean needAllWait() default true;
}

View File

@ -1,6 +1,7 @@
package com.chaozhanggui.system.cashierservice.controller;
import cn.hutool.core.util.ObjectUtil;
import com.chaozhanggui.system.cashierservice.annotation.LimitSubmit;
import com.chaozhanggui.system.cashierservice.service.PayService;
import com.chaozhanggui.system.cashierservice.sign.Result;
import com.chaozhanggui.system.cashierservice.util.IpUtil;
@ -33,6 +34,7 @@ public class PayController {
* @return
*/
@RequestMapping("orderPay")
@LimitSubmit(key = "orderPay:%s")
public Result pay(HttpServletRequest request, @RequestHeader("openId") String openId, @RequestBody Map<String, String> map) {
if (ObjectUtil.isEmpty(map) || map.size() <= 0 || !map.containsKey("orderId") || ObjectUtil.isEmpty(map.get("orderId"))) {
return Result.fail("订单号不允许为空");
@ -139,6 +141,7 @@ public class PayController {
* @return
*/
@RequestMapping("memeberIn")
@LimitSubmit(key = "memeberIn:%s")
public Result memeberIn(HttpServletRequest request, @RequestHeader("openId") String openId, @RequestHeader("id") String id,
@RequestBody Map<String, Object> map
) {

View File

@ -152,4 +152,17 @@ public class DefaultExceptionAdvice {
return new ResponseEntity<>(response, HttpStatus.OK);
}
/**
* 使用ExceptionHandler注解声明处理TestException异常
*
*/
@ResponseBody
@ExceptionHandler(MsgException.class)
public Result exception(MsgException e) {
// 控制台打印异常
e.printStackTrace();
// 返回错误格式信息
return Result.fail(e.getMessage());
}
}

View File

@ -0,0 +1,186 @@
package com.chaozhanggui.system.cashierservice.interceptor;
import cn.hutool.core.util.ObjectUtil;
import com.chaozhanggui.system.cashierservice.annotation.LimitSubmit;
import com.chaozhanggui.system.cashierservice.exception.MsgException;
import com.chaozhanggui.system.cashierservice.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
@Component
@Aspect
@Slf4j
public class LimitSubmitAspect {
//封装了redis操作各种方法
@Autowired
private RedisUtils redisUtil;
@Pointcut("@annotation(com.chaozhanggui.system.cashierservice.annotation.LimitSubmit)")
private void pay() {
}
@Pointcut("@annotation(com.chaozhanggui.system.cashierservice.annotation.LimitSubmit)")
private void pay1() {
}
@Around("pay()")
public Object handleSubmit(ProceedingJoinPoint joinPoint) throws Throwable {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String orderId= request.getParameter("orderId");
if(ObjectUtil.isEmpty(orderId)||ObjectUtil.isNull(orderId)){
orderId=request.getParameter("authCode");
}
if(ObjectUtil.isEmpty(orderId)||ObjectUtil.isNull(orderId)){
orderId=request.getParameter("id");
}
//获取注解信息
LimitSubmit limitSubmit = method.getAnnotation(LimitSubmit.class);
boolean needAllWait = limitSubmit.needAllWait();
String redisKey = limitSubmit.key();
int submitTimeLimiter = limitSubmit.limit();
String key = getRedisKey(joinPoint, redisKey, orderId);
Object result = redisUtil.get(key);
log.info("开始锁定资源信息" + key);
if (result != null) {
log.info("锁定的值是" + result.toString());
throw new MsgException("正在处理中, 请勿重复操作");
}
boolean setResult = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), submitTimeLimiter);
if (!setResult) {
throw new MsgException("1正在处理中, 请勿重复操作");
}
try {
Object proceed = joinPoint.proceed();
return proceed;
} catch (Throwable e) {
log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null ? e.getCause() : "NULL", e.getMessage(), e);
throw e;
} finally {
if (!needAllWait) {
redisUtil.del(redisKey);
log.info("删除后的结果: " + redisUtil.get(redisKey));
}
}
}
@AfterReturning("pay1()")
public void AfterReturning(JoinPoint joinPoint) {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
LimitSubmit limitSubmit = method.getAnnotation(LimitSubmit.class);
String redisKey = limitSubmit.key();
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String orderId= request.getParameter("orderId");
String key = getRedisKey1(joinPoint, redisKey, orderId);
log.info("正常释放了锁资源" + key);
// 延时 1s 释放
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// redisUtil.del(key);
log.info("删除后的结果: " + redisUtil.get(redisKey));
}
}
@AfterThrowing(pointcut = "pay1()", throwing = "ex")
public void AfterThrowing(JoinPoint joinPoint, Throwable ex) {
if (!(ex instanceof MsgException)) {
// 抛出的如果不是重复性提交的异常, 则释放锁资源
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
LimitSubmit limitSubmit = method.getAnnotation(LimitSubmit.class);
String redisKey = limitSubmit.key();
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String orderId= request.getParameter("orderId");
String key = getRedisKey1(joinPoint, redisKey, orderId);
log.info("发生异常释放了锁资源" + key);
// 延时 1s 释放
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
redisUtil.del(key);
log.info("删除后的结果: " + redisUtil.get(redisKey));
}
}
}
/**
* 支持多参数从请求参数进行处理
*/
private String getRedisKey(ProceedingJoinPoint joinPoint, String key, String orderId) {
if (key.contains("%s") && orderId != null) {
key = String.format(key, orderId);
}
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
String[] parameterNames = discoverer.getParameterNames(method);
if (parameterNames != null) {
for (int i = 0; i < parameterNames.length; i++) {
String item = parameterNames[i];
if (key.contains("#" + item)) {
key = key.replace("#" + item, joinPoint.getArgs()[i].toString());
}
}
}
return key.toString();
}
private String getRedisKey1(JoinPoint joinPoint, String key, String orderId) {
if (key.contains("%s") && orderId != null) {
key = String.format(key, orderId);
}
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
String[] parameterNames = discoverer.getParameterNames(method);
if (parameterNames != null) {
for (int i = 0; i < parameterNames.length; i++) {
String item = parameterNames[i];
if (key.contains("#" + item)) {
key = key.replace("#" + item, joinPoint.getArgs()[i].toString());
}
}
}
return key.toString();
}
}

View File

@ -1,163 +1,51 @@
package com.chaozhanggui.system.cashierservice.util;
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author /
*/
@Component
@SuppressWarnings({"unchecked", "all"})
public class RedisUtils {
private static final Logger log = LoggerFactory.getLogger(RedisUtils.class);
@Resource
private RedisTemplate<Object, Object> redisTemplate;
@Value("${jwt.online-key}")
private String onlineKey;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 指定缓存失效时间
*
* @param key
* @param time 时间()
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
return true;
}
/**
* 指定缓存失效时间
*
* @param key
* @param time 时间()
* @param timeUnit 单位
*/
public boolean expire(String key, long time, TimeUnit timeUnit) {
try {
if (time > 0) {
redisTemplate.expire(key, time, timeUnit);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
return true;
}
/**
* 根据 key 获取过期时间
* 根据key 获取过期时间
*
* @param key 不能为null
* @return 时间() 返回0代表为永久有效
*/
public long getExpire(Object key) {
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 查找匹配key
*
* @param pattern key
* @return /
*/
public List<String> scan(String pattern) {
ScanOptions options = ScanOptions.scanOptions().match(pattern).build();
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection rc = Objects.requireNonNull(factory).getConnection();
Cursor<byte[]> cursor = rc.scan(options);
List<String> result = new ArrayList<>();
while (cursor.hasNext()) {
result.add(new String(cursor.next()));
}
try {
RedisConnectionUtils.releaseConnection(rc, factory);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return result;
}
/**
* 分页查询 key
*
* @param patternKey key
* @param page 页码
* @param size 每页数目
* @return /
*/
public List<String> findKeysForPage(String patternKey, int page, int size) {
ScanOptions options = ScanOptions.scanOptions().match(patternKey).build();
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection rc = Objects.requireNonNull(factory).getConnection();
Cursor<byte[]> cursor = rc.scan(options);
List<String> result = new ArrayList<>(size);
int tmpIndex = 0;
int fromIndex = page * size;
int toIndex = page * size + size;
while (cursor.hasNext()) {
if (tmpIndex >= fromIndex && tmpIndex < toIndex) {
result.add(new String(cursor.next()));
tmpIndex++;
continue;
}
// 获取到满足条件的数据后,就可以退出了
if (tmpIndex >= toIndex) {
break;
}
tmpIndex++;
cursor.next();
}
try {
RedisConnectionUtils.releaseConnection(rc, factory);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return result;
}
/**
* 判断key是否存在
*
@ -168,7 +56,7 @@ public class RedisUtils {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
}
@ -178,23 +66,13 @@ public class RedisUtils {
*
* @param key 可以传一个值 或多个
*/
public void del(String... keys) {
if (keys != null && keys.length > 0) {
if (keys.length == 1) {
boolean result = redisTemplate.delete(keys[0]);
log.debug("--------------------------------------------");
log.debug(new StringBuilder("删除缓存:").append(keys[0]).append(",结果:").append(result).toString());
log.debug("--------------------------------------------");
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
Set<Object> keySet = new HashSet<>();
for (String key : keys) {
keySet.addAll(redisTemplate.keys(key));
}
long count = redisTemplate.delete(keySet);
log.debug("--------------------------------------------");
log.debug("成功删除缓存:" + keySet.toString());
log.debug("缓存删除数量:" + count + "");
log.debug("--------------------------------------------");
redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
}
}
}
@ -211,19 +89,6 @@ public class RedisUtils {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 批量获取
*
* @param keys
* @return
*/
public List<Object> multiGet(List<String> keys) {
List list = redisTemplate.opsForValue().multiGet(Sets.newHashSet(keys));
List resultList = Lists.newArrayList();
Optional.ofNullable(list).ifPresent(e-> list.forEach(ele-> Optional.ofNullable(ele).ifPresent(resultList::add)));
return resultList;
}
/**
* 普通缓存放入
*
@ -236,9 +101,10 @@ public class RedisUtils {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
}
/**
@ -258,60 +124,37 @@ public class RedisUtils {
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 普通缓存放入并设置时间重写
*
* @param key
* @param value
* @param time 时间
* @param timeUnit 类型
* @return true成功 false 失败
*/
public boolean setextend(String key, Object value, long time) {
try {
if (time > 0) {
stringRedisTemplate.opsForValue().set(key, value.toString(), time);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
}
public Long strincrement(String key, long delta) {
return stringRedisTemplate.opsForValue().increment(key, delta);
/**
* 递增
*
* @param key
* @param by 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 普通缓存放入并设置时间
* 递减
*
* @param key
* @param value
* @param time 时间
* @param timeUnit 类型
* @return true成功 false 失败
* @param key
* @param by 要减少几(小于0)
* @return
*/
public boolean set(String key, String value, long time, TimeUnit timeUnit) {
try {
if (time > 0) {
stringRedisTemplate.opsForValue().set(key, value, time, timeUnit);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
@ -335,7 +178,6 @@ public class RedisUtils {
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
@ -350,7 +192,7 @@ public class RedisUtils {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
}
@ -371,7 +213,7 @@ public class RedisUtils {
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
}
@ -389,7 +231,7 @@ public class RedisUtils {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
}
@ -411,7 +253,7 @@ public class RedisUtils {
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
}
@ -473,7 +315,7 @@ public class RedisUtils {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return null;
}
}
@ -489,7 +331,7 @@ public class RedisUtils {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
}
@ -505,7 +347,7 @@ public class RedisUtils {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return 0;
}
}
@ -526,7 +368,7 @@ public class RedisUtils {
}
return count;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return 0;
}
}
@ -541,7 +383,7 @@ public class RedisUtils {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return 0;
}
}
@ -558,11 +400,10 @@ public class RedisUtils {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
@ -577,7 +418,7 @@ public class RedisUtils {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return null;
}
}
@ -592,7 +433,7 @@ public class RedisUtils {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return 0;
}
}
@ -608,7 +449,7 @@ public class RedisUtils {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return null;
}
}
@ -618,6 +459,7 @@ public class RedisUtils {
*
* @param key
* @param value
* @param time 时间()
* @return
*/
public boolean lSet(String key, Object value) {
@ -625,7 +467,7 @@ public class RedisUtils {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
}
@ -646,7 +488,7 @@ public class RedisUtils {
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
}
@ -656,6 +498,7 @@ public class RedisUtils {
*
* @param key
* @param value
* @param time 时间()
* @return
*/
public boolean lSet(String key, List<Object> value) {
@ -663,7 +506,7 @@ public class RedisUtils {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
}
@ -684,7 +527,7 @@ public class RedisUtils {
}
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
}
@ -695,14 +538,14 @@ public class RedisUtils {
* @param key
* @param index 索引
* @param value
* @return /
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return false;
}
}
@ -717,74 +560,27 @@ public class RedisUtils {
*/
public long lRemove(String key, long count, Object value) {
try {
return redisTemplate.opsForList().remove(key, count, value);
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
return 0;
}
}
/**
* @param prefix 前缀
* @param ids id
*/
public void delByKeys(String prefix, Set<Long> ids) {
Set<Object> keys = new HashSet<>();
for (Long id : ids) {
keys.addAll(redisTemplate.keys(new StringBuffer(prefix).append(id).toString()));
* @Description 上锁并设置过期时间
* @Date 15:09 2023/7/7
* @Param [key, value, time]
* @return boolean
**/
public boolean setIfAbsent(String key, Object value, long time) {
try {
return redisTemplate.opsForValue().setIfAbsent(key, value, time, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
return false;
}
long count = redisTemplate.delete(keys);
// 此处提示可自行删除
log.debug("--------------------------------------------");
log.debug("成功删除缓存:" + keys.toString());
log.debug("缓存删除数量:" + count + "");
log.debug("--------------------------------------------");
}
String secKillScript = "local userid=KEYS[1];\r\n" +
"local prodid=KEYS[2];\r\n" +
"local qtkey=prodid;\r\n" +
"local usernum=KEYS[3];\r\n" +
"local usersKey='sk:'..prodid..\":usr\";\r\n" +
"local num= redis.call(\"get\" ,qtkey);\r\n" +
"if tonumber(num)<tonumber(usernum) then \r\n" +
" return 0;\r\n" +
"end\r\n" +
"if tonumber(num)<=0 then \r\n" +
" return 0;\r\n" +
"else \r\n" +
" redis.call(\"DECRBY\",qtkey,tonumber(usernum));\r\n" +
"end\r\n" +
"return 1";
public String seckill(String key, String prodid,String num,String uid) {
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
redisScript.setResultType(Long.class);//返回类型是Long
redisScript.setScriptText(secKillScript);
Object execute = redisTemplate.execute(redisScript, Arrays.asList(uid, key,num), prodid);
String reString = String.valueOf(execute);
return reString;
}
String secAddScript = "local prodid=KEYS[1];\r\n" +
"local usernum=KEYS[2];\r\n" +
"local num= redis.call(\"get\" ,prodid);\r\n" +
" redis.call(\"SET\",prodid,tonumber(usernum)+tonumber(num));\r\n" +
"return 1";
public String secAdd(String key,String num) {
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
redisScript.setResultType(Long.class);//返回类型是Long
redisScript.setScriptText(secKillScript);
Object execute = redisTemplate.execute(redisScript, Arrays.asList(key,num));
String reString = String.valueOf(execute);
return reString;
}
public boolean lock(String key, long timeout, TimeUnit timeUnit) {
String value = UUID.randomUUID().toString();
Boolean success = redisTemplate.opsForValue().setIfAbsent(key, value, timeout, timeUnit);
return success != null && success;
}
public void releaseLock(String key) {
redisTemplate.delete(key);
}
}
}