当前位置:   article > 正文

SpringBoot接口防重复和日志切面_localvariabletableparameternamediscoverer未找到

localvariabletableparameternamediscoverer未找到

简单通过redis过期处理接口重复和日志切面token+ip+参数+spel表单式

引入redis依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>

yaml配置redis

  1. spring
  2. redis:
  3. host: 10.*.*.37
  4. password: ***
  5. database: 12
  6. port: 6379

防重复切面注解

  1. import java.lang.annotation.ElementType;
  2. import java.lang.annotation.Retention;
  3. import java.lang.annotation.RetentionPolicy;
  4. import java.lang.annotation.Target;
  5. /**
  6. * Description VaildApiRecommit
  7. *
  8. * @ClassName VaildApiRecommit
  9. * @date 2023.03.20 19:27
  10. **/
  11. @Target(value = ElementType.METHOD)
  12. @Retention(RetentionPolicy.RUNTIME)
  13. public @interface VaildApiRecommit {
  14. /**
  15. * Description ConstantUtils.EXTAPIHEAD 是否从header头部获取到Authorization 不配置则从参数获取
  16. **/
  17. String value();
  18. /**
  19. * 提交唯一标识组合 遵循spel表达式
  20. * primaryKeys = "#processDefineKey"
  21. */
  22. String[] primaryKeys() default {};
  23. /**
  24. * 校验时间间隔,如果指定覆盖默认系统属性值
  25. */
  26. long validateInterval() default 3;
  27. }

接口防重复切面

  1. import java.lang.reflect.Method;
  2. import java.math.BigInteger;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import javax.annotation.Resource;
  6. import javax.servlet.http.HttpServletRequest;
  7. import org.apache.commons.lang3.StringUtils;
  8. import org.aspectj.lang.JoinPoint;
  9. import org.aspectj.lang.annotation.AfterThrowing;
  10. import org.aspectj.lang.annotation.Aspect;
  11. import org.aspectj.lang.annotation.Before;
  12. import org.aspectj.lang.annotation.Pointcut;
  13. import org.aspectj.lang.reflect.MethodSignature;
  14. import org.springframework.beans.factory.annotation.Value;
  15. import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
  16. import org.springframework.core.annotation.AnnotationUtils;
  17. import org.springframework.core.annotation.Order;
  18. import org.springframework.expression.EvaluationContext;
  19. import org.springframework.expression.Expression;
  20. import org.springframework.expression.ExpressionParser;
  21. import org.springframework.expression.spel.standard.SpelExpressionParser;
  22. import org.springframework.expression.spel.support.StandardEvaluationContext;
  23. import org.springframework.stereotype.Component;
  24. import org.springframework.util.CollectionUtils;
  25. import org.springframework.util.DigestUtils;
  26. import org.springframework.web.context.request.RequestContextHolder;
  27. import org.springframework.web.context.request.ServletRequestAttributes;
  28. import com.alibaba.fastjson.JSON;
  29. import com.adapter.common.base.exception.BusinessException;
  30. import com.adapter.common.base.redis.ConstantUtils;
  31. import com.adapter.utils.RedisUtil;
  32. import cn.hutool.core.util.StrUtil;
  33. /**
  34. * Description ExtApiAopIdempotent
  35. *
  36. * @ClassName ExtApiAopIdempotent
  37. * @date 2023.03.20 19:28
  38. **/
  39. @Order(0)
  40. @Aspect
  41. @Component
  42. public class ValidApiRecommitAspect {
  43. @Resource
  44. private RedisUtil redisUtil;
  45. @Value("${app.validateInterval}")
  46. private Long validateInterval;
  47. @Pointcut("execution(* com.adapter.api..*.*(..))")
  48. public void rlAop() {
  49. }
  50. /**
  51. * 封装数据
  52. */
  53. public HttpServletRequest getRequest() {
  54. ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
  55. HttpServletRequest request = attributes.getRequest();
  56. return request;
  57. }
  58. /**
  59. * 异常返回通知,连接点抛出异常
  60. *
  61. * @param joinPoint
  62. * 切入点
  63. * @param e
  64. * 异常信息
  65. */
  66. @AfterThrowing(pointcut = "rlAop()", throwing = "e")
  67. public void saveExceptionOperateLog(JoinPoint joinPoint, Throwable e) {
  68. throw BusinessException.create("重复提交检验失败" + e.getMessage());
  69. }
  70. @Before("rlAop()")
  71. public void before(JoinPoint joinPoint) {
  72. // 获取被增强的方法相关信息 - 查看方法上是否有次注解
  73. MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
  74. Method method = methodSignature.getMethod();
  75. VaildApiRecommit declaredAnnotation = AnnotationUtils.findAnnotation(method, VaildApiRecommit.class);
  76. if (declaredAnnotation != null) {
  77. String values = declaredAnnotation.value();
  78. String token = null;
  79. HttpServletRequest request = getRequest();
  80. if (values.equals(ConstantUtils.EXTAPIHEAD)) {
  81. token = request.getHeader("Authorization");
  82. } else {
  83. token = request.getParameter("Authorization");
  84. }
  85. // 获取不到token
  86. if (StrUtil.isEmpty(token)) {
  87. throw BusinessException.create("未找到鉴权头部信息");
  88. }
  89. // 存入redis的键token + method + ip + 参数
  90. String key = getValidateKey(method, joinPoint.getArgs(), declaredAnnotation.primaryKeys(), token);
  91. // 接口获取对应的令牌,如果能够获取该(从redis获取令牌)令牌(将当前令牌删除掉) 就直接执行该访问的业务逻辑
  92. boolean isToken = redisUtil.hasKey(key);
  93. // 接口获取对应的令牌,如果获取不到该令牌 直接返回请勿重复提交
  94. if (isToken) {
  95. throw BusinessException.create("请勿重复请求");
  96. } else {
  97. redisUtil.set(key, key, validateInterval);
  98. }
  99. }
  100. }
  101. /**
  102. * 获取每次请求Key token + ip+uri+paramsKey
  103. */
  104. private String getValidateKey(Method method, Object[] args, String[] primaryKeys, String token) {
  105. List<String> paramsKey = evalParamsKey(method, args, primaryKeys);
  106. ServletRequestAttributes requestAttributes =
  107. (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
  108. HttpServletRequest request = requestAttributes.getRequest();
  109. String requestURI = request.getRequestURI();
  110. String userIp = request.getRemoteAddr();
  111. StringBuilder requestKey = new StringBuilder();
  112. requestKey.append(token);
  113. if (StringUtils.isNotEmpty(userIp)) {
  114. requestKey.append(userIp);
  115. }
  116. if (StringUtils.isNotEmpty(requestURI)) {
  117. requestKey.append(requestURI);
  118. }
  119. if (!CollectionUtils.isEmpty(paramsKey)) {
  120. for (String primaryValue : paramsKey) {
  121. requestKey.append(primaryValue);
  122. }
  123. }
  124. if (CollectionUtils.isEmpty(paramsKey) && args != null) {
  125. for (Object primaryValue : args) {
  126. if (primaryValue != null) {
  127. requestKey.append(JSON.toJSONString(primaryValue));
  128. }
  129. }
  130. }
  131. // key压缩
  132. return new BigInteger(1, DigestUtils.md5Digest(requestKey.toString().getBytes())).toString(16);
  133. }
  134. /**
  135. * Description 解析Spel表达式获取值
  136. *
  137. * @param method
  138. * method
  139. * @param args
  140. * 请求的参数
  141. * @param primaryKeys
  142. * spel表达式
  143. * @return java.util.List<java.lang.String>
  144. * @author
  145. * @date 20:10 2023/3/20
  146. **/
  147. private List<String> evalParamsKey(Method method, Object[] args, String[] primaryKeys) {
  148. List<String> primaryValues = new ArrayList<>();
  149. if (primaryKeys != null) {
  150. for (String primaryKey : primaryKeys) {
  151. ExpressionParser expressionParser = new SpelExpressionParser();
  152. Expression expression = expressionParser.parseExpression(primaryKey);
  153. EvaluationContext context = new StandardEvaluationContext();
  154. LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
  155. String[] parameterNames = discoverer.getParameterNames(method);
  156. for (int i = 0; i < parameterNames.length; i++) {
  157. if (args[i] != null) {
  158. context.setVariable(parameterNames[i], args[i]);
  159. }
  160. }
  161. Object primaryValue = expression.getValue(context);
  162. if (primaryValue != null) {
  163. primaryValues.add(JSON.toJSONString(primaryValue));
  164. }
  165. }
  166. }
  167. return primaryValues;
  168. }
  169. }

日志切面

  1. import java.lang.annotation.*;
  2. /**
  3. * @description: 用户行为日志注解
  4. *
  5. */
  6. @Target({ElementType.METHOD})
  7. @Retention(RetentionPolicy.RUNTIME)
  8. @Documented
  9. public @interface BusinessOperateLog {
  10. /**
  11. * 操作模块
  12. * @return : java.lang.String
  13. */
  14. String operateModule() default "";
  15. /**
  16. * 操作类型
  17. * @return
  18. */
  19. String operateType() default "";
  20. /**
  21. * 操作说明
  22. * @return
  23. */
  24. String operateDesc() default "";
  25. }
  1. import cn.hutool.core.util.ObjectUtil;
  2. import cn.hutool.json.JSONUtil;
  3. import com.adapter.dto.log.ManageOperateDTO;
  4. import com.adapter.service.ManageOperateService;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.aspectj.lang.JoinPoint;
  7. import org.aspectj.lang.annotation.AfterReturning;
  8. import org.aspectj.lang.annotation.AfterThrowing;
  9. import org.aspectj.lang.annotation.Aspect;
  10. import org.aspectj.lang.annotation.Pointcut;
  11. import org.aspectj.lang.reflect.MethodSignature;
  12. import org.springframework.core.annotation.AnnotationUtils;
  13. import org.springframework.core.annotation.Order;
  14. import org.springframework.stereotype.Component;
  15. import javax.annotation.Resource;
  16. import java.lang.reflect.Method;
  17. import java.util.Date;
  18. /**
  19. * @description: 系统日志
  20. */
  21. @Order(2)
  22. @Aspect
  23. @Component
  24. @Slf4j
  25. public class SysLogAspect {
  26. //日志持久类
  27. @Resource
  28. private ManageOperateService manageOperateService;
  29. /****************************************************
  30. * 系统行为日志
  31. ********************************************************/
  32. /**
  33. * 注解切入点
  34. */
  35. @Pointcut(
  36. value = "execution(* com.adapter.api..*.*(..))")
  37. public void operateLogPointCut() {
  38. // 这是一个切入点
  39. }
  40. /**
  41. * 前端用户操作行为成功
  42. */
  43. private static final String OPERATE_STATUS_SUCCESS = "1";
  44. /**
  45. * 前端用户操作行为失败
  46. */
  47. private static final String OPERATE_STATUS_FAIL = "0";
  48. /**
  49. * 正常返回通知,拦截用户操作日志,连接点正常执行完成后执行, 如果连接点抛出异常,则不会执行
  50. *
  51. * @param joinPoint
  52. * 切入点
  53. * @param keys
  54. * 返回结果
  55. */
  56. @AfterReturning(value = "operateLogPointCut()", returning = "keys")
  57. public void saveOperateLog(JoinPoint joinPoint, Object keys) {
  58. operate(joinPoint, OPERATE_STATUS_SUCCESS);
  59. }
  60. /**
  61. * 异常返回通知,用于拦截异常日志信息 连接点抛出异常后执行
  62. *
  63. * @param joinPoint
  64. * 切入点
  65. * @param e
  66. * 异常信息
  67. */
  68. @AfterThrowing(pointcut = "operateLogPointCut()", throwing = "e")
  69. public void saveExceptionOperateLog(JoinPoint joinPoint, Throwable e) {
  70. operate(joinPoint, OPERATE_STATUS_FAIL);
  71. }
  72. private void operate(JoinPoint joinPoint, String operateStatus) {
  73. // 从切面织入点处通过反射机制获取织入点处的方法
  74. MethodSignature signature = (MethodSignature)joinPoint.getSignature();
  75. // 获取切入点所在的方法
  76. Method method = signature.getMethod();
  77. String s = JSONUtil.toJsonStr(joinPoint.getArgs());
  78. log.info("保存到日志中的参数是:{}", s);
  79. // 获取操作
  80. BusinessOperateLog businessOperateLog = AnnotationUtils.findAnnotation(method, BusinessOperateLog.class);
  81. if (ObjectUtil.isNotEmpty(businessOperateLog)) {
  82. String desc = "【" + businessOperateLog.operateModule() + "】" + "-【" + businessOperateLog.operateType()
  83. + "】," + businessOperateLog.operateDesc() + ",参数:" + s;
  84. ManageOperateDTO manageOperateDTO = new ManageOperateDTO();
  85. // manageOperateDTO.setManageUserId(SecurityUtil.currentUserId());
  86. manageOperateDTO.setOperateTime(new Date());
  87. manageOperateDTO.setOperateStatus(operateStatus);
  88. manageOperateDTO.setOperateContent(desc);
  89. // manageOperateDTO.setCreator(SecurityUtil.getCurrentUser().getUserName());
  90. // manageOperateDTO.setAreaCode(SecurityUtil.getVaildCodes());
  91. manageOperateService.add(manageOperateDTO);
  92. }
  93. }
  94. }

注解使用

  1. public class OperateType {
  2. private OperateType() {}
  3. /**
  4. * 新增
  5. */
  6. public final static String ADD = "ADD";
  7. /**
  8. * 修改
  9. */
  10. public final static String UPDATE = "UPDATE";
  11. /**
  12. * 删除
  13. */
  14. public final static String DELETE = "DELETE";
  15. /**
  16. * 批量删除
  17. */
  18. public final static String BATCH_DELETE = "BATCH_DELETE";
  19. /**
  20. * 查询
  21. */
  22. public final static String QUERY = "QUERY";
  23. /**
  24. * 导出
  25. */
  26. public final static String EXPORT = "EXPORT";
  27. /**
  28. * 导入
  29. */
  30. public final static String IMPORT = "IMPORT";
  31. /**
  32. * 审核
  33. */
  34. public final static String AUDIT = "AUDIT";
  35. }
  36. /**
  37. * 新增
  38. *
  39. * @param entity entity
  40. * @return boolean
  41. */
  42. @VaildApiRecommit(value = ConstantUtils.EXTAPIHEAD)
  43. @ApiOperation(value = "新增", notes = "新增")
  44. @PostMapping("/add")
  45. @BusinessOperateLog(operateModule = "接口新增", operateType = OperateType.ADD, operateDesc = "新增接口")
  46. public JsonResponse<Boolean> add(@RequestBody @ApiParam(value = "新增数据类", name = "entity") T entity) {
  47. return JsonResponse.ok(baseService.insert(entity));
  48. }

redis工具类

  1. import com.adapter.common.base.exception.BusinessException;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.data.redis.core.RedisTemplate;
  4. import org.springframework.stereotype.Component;
  5. import org.springframework.util.CollectionUtils;
  6. import javax.annotation.Resource;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Set;
  10. import java.util.concurrent.TimeUnit;
  11. @Component
  12. @Slf4j
  13. public class RedisUtil {
  14. @Resource
  15. private RedisTemplate<String, Object> redisTemplate;
  16. private final static String GET_ERROR_MESSAGE = "获取缓存数据失败";
  17. private final static String SET_ERROR_MESSAGE = "设置缓存数据失败";
  18. private final static String DELETE_ERROR_MESSAGE = "删除缓存数据失败";
  19. /**
  20. * 根据keys pattern 进行模糊匹配查询存在的key值
  21. *
  22. * @param keys K pattern
  23. * @return
  24. */
  25. public Set<String> keys(String keys) {
  26. try {
  27. return redisTemplate.keys(keys);
  28. } catch (Exception e) {
  29. log.error(e.getMessage());
  30. throw BusinessException.create(GET_ERROR_MESSAGE);
  31. }
  32. }
  33. /**
  34. * 指定缓存失效时间
  35. *
  36. * @param key 键
  37. * @param time 时间(秒)
  38. * @return
  39. */
  40. public boolean expire(String key, long time) {
  41. try {
  42. if (time > 0) {
  43. redisTemplate.expire(key, time, TimeUnit.SECONDS);
  44. }
  45. return true;
  46. } catch (Exception e) {
  47. e.printStackTrace();
  48. log.error(e.getMessage());
  49. throw BusinessException.create("插入缓存数据失败");
  50. //return false;
  51. }
  52. }
  53. /**
  54. * 根据key 获取过期时间
  55. *
  56. * @param key 键 不能为null
  57. * @return 时间(秒) 返回0代表为永久有效
  58. */
  59. public long getExpire(String key) {
  60. return redisTemplate.getExpire(key, TimeUnit.SECONDS);
  61. }
  62. /**
  63. * 判断key是否存在
  64. *
  65. * @param key 键
  66. * @return true 存在 false不存在
  67. */
  68. public boolean hasKey(String key) {
  69. try {
  70. return redisTemplate.hasKey(key);
  71. } catch (Exception e) {
  72. //e.printStackTrace();
  73. log.error(e.getMessage());
  74. throw BusinessException.create("判断缓存数据失败");
  75. //return false;
  76. }
  77. }
  78. /**
  79. * 删除缓存
  80. *
  81. * @param key 可以传一个值 或多个
  82. */
  83. @SuppressWarnings("unchecked")
  84. public void del(String... key) {
  85. if (key != null && key.length > 0) {
  86. try {
  87. if (key.length == 1) {
  88. redisTemplate.delete(key[0]);
  89. } else {
  90. redisTemplate.delete(CollectionUtils.arrayToList(key));
  91. }
  92. } catch (Exception e) {
  93. log.error(e.getMessage());
  94. throw BusinessException.create("删除缓存数据失败");
  95. }
  96. }
  97. }
  98. /**
  99. * 普通缓存获取
  100. *
  101. * @param key 键
  102. * @return
  103. */
  104. public Object get(String key) {
  105. try {
  106. return key == null ? null : redisTemplate.opsForValue().get(key);
  107. } catch (Exception e) {
  108. e.printStackTrace();
  109. log.error(e.getMessage());
  110. throw BusinessException.create(GET_ERROR_MESSAGE);
  111. }
  112. }
  113. /**
  114. * 普通缓存放入
  115. *
  116. * @param key 键
  117. * @param value 值
  118. * @return true成功 false失败
  119. */
  120. public boolean set(String key, Object value) {
  121. try {
  122. redisTemplate.opsForValue().set(key, value);
  123. return true;
  124. } catch (Exception e) {
  125. //e.printStackTrace();
  126. log.error(e.getMessage());
  127. throw BusinessException.create("插入缓存数据失败");
  128. //return false;
  129. }
  130. }
  131. /**
  132. * 普通缓存放入并设置时间
  133. *
  134. * @param key 键
  135. * @param value 值
  136. * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
  137. * @return true成功 false 失败
  138. */
  139. public boolean set(String key, Object value, long time) {
  140. try {
  141. if (time > 0) {
  142. redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
  143. } else {
  144. set(key, value);
  145. }
  146. return true;
  147. } catch (Exception e) {
  148. e.printStackTrace();
  149. log.error(e.getMessage());
  150. throw BusinessException.create("插入缓存数据失败");
  151. //return false;
  152. }
  153. }
  154. /**
  155. * 递增
  156. *
  157. * @param key 键
  158. * @param delta 要增加几(大于0)
  159. * @return
  160. */
  161. public long incr(String key, long delta) {
  162. if (delta < 0) {
  163. throw new RuntimeException("递增因子必须大于0");
  164. }
  165. return redisTemplate.opsForValue().increment(key, delta);
  166. }
  167. /**
  168. * 递减
  169. *
  170. * @param key 键
  171. * @param delta 要减少几(小于0)
  172. * @return
  173. */
  174. public long decr(String key, long delta) {
  175. if (delta < 0) {
  176. throw new RuntimeException("递减因子必须大于0");
  177. }
  178. return redisTemplate.opsForValue().increment(key, -delta);
  179. }
  180. // ===============================Hash=================================
  181. /**
  182. * HashGet
  183. *
  184. * @param key 键 不能为null
  185. * @param item 项 不能为null
  186. * @return
  187. */
  188. public Object hget(String key, String item) {
  189. try {
  190. return redisTemplate.opsForHash().get(key, item);
  191. } catch (Exception e) {
  192. log.error(e.getMessage());
  193. throw BusinessException.create(GET_ERROR_MESSAGE);
  194. }
  195. }
  196. /**
  197. * 获取hashKey对应的所有键值
  198. *
  199. * @param key 键
  200. * @return 对应的多个键值
  201. */
  202. public Map<Object, Object> hmget(String key) {
  203. try {
  204. return redisTemplate.opsForHash().entries(key);
  205. } catch (Exception e) {
  206. log.error(e.getMessage());
  207. throw BusinessException.create(GET_ERROR_MESSAGE);
  208. }
  209. }
  210. /**
  211. * HashSet
  212. *
  213. * @param key 键
  214. * @param map 对应多个键值
  215. * @return true 成功 false 失败
  216. */
  217. public boolean hmset(String key, Map<String, Object> map) {
  218. try {
  219. redisTemplate.opsForHash().putAll(key, map);
  220. return true;
  221. } catch (Exception e) {
  222. //e.printStackTrace();
  223. log.error(e.getMessage());
  224. throw BusinessException.create(GET_ERROR_MESSAGE);
  225. //return false;
  226. }
  227. }
  228. /**
  229. * HashSet 并设置时间
  230. *
  231. * @param key 键
  232. * @param map 对应多个键值
  233. * @param time 时间(秒)
  234. * @return true成功 false失败
  235. */
  236. public boolean hmset(String key, Map<String, Object> map, long time) {
  237. try {
  238. redisTemplate.opsForHash().putAll(key, map);
  239. if (time > 0) {
  240. expire(key, time);
  241. }
  242. return true;
  243. } catch (Exception e) {
  244. //e.printStackTrace();
  245. log.error(e.getMessage());
  246. throw BusinessException.create(GET_ERROR_MESSAGE);
  247. //return false;
  248. }
  249. }
  250. /**
  251. * 向一张hash表中放入数据,如果不存在将创建
  252. *
  253. * @param key 键
  254. * @param item 项
  255. * @param value 值
  256. * @return true 成功 false失败
  257. */
  258. public boolean hset(String key, String item, Object value) {
  259. try {
  260. redisTemplate.opsForHash().put(key, item, value);
  261. return true;
  262. } catch (Exception e) {
  263. //e.printStackTrace();
  264. log.error(e.getMessage());
  265. throw BusinessException.create(GET_ERROR_MESSAGE);
  266. //return false;
  267. }
  268. }
  269. /**
  270. * 向一张hash表中放入数据,如果不存在将创建
  271. *
  272. * @param key 键
  273. * @param item 项
  274. * @param value 值
  275. * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
  276. * @return true 成功 false失败
  277. */
  278. public boolean hset(String key, String item, Object value, long time) {
  279. try {
  280. redisTemplate.opsForHash().put(key, item, value);
  281. if (time > 0) {
  282. expire(key, time);
  283. }
  284. return true;
  285. } catch (Exception e) {
  286. //e.printStackTrace();
  287. log.error(e.getMessage());
  288. throw BusinessException.create(GET_ERROR_MESSAGE);
  289. //return false;
  290. }
  291. }
  292. /**
  293. * 删除hash表中的值
  294. *
  295. * @param key 键 不能为null
  296. * @param item 项 可以使多个 不能为null
  297. */
  298. public void hdel(String key, Object... item) {
  299. try {
  300. redisTemplate.opsForHash().delete(key, item);
  301. } catch (Exception e) {
  302. log.error(e.getMessage());
  303. throw BusinessException.create("删除缓存数据失败");
  304. }
  305. }
  306. /**
  307. * 判断hash表中是否有该项的值
  308. *
  309. * @param key 键 不能为null
  310. * @param item 项 不能为null
  311. * @return true 存在 false不存在
  312. */
  313. public boolean hHasKey(String key, String item) {
  314. try {
  315. return redisTemplate.opsForHash().hasKey(key, item);
  316. } catch (Exception e) {
  317. log.error(e.getMessage());
  318. throw BusinessException.create(GET_ERROR_MESSAGE);
  319. }
  320. }
  321. /**
  322. * hash递增 如果不存在,就会创建一个 并把新增后的值返回
  323. *
  324. * @param key 键
  325. * @param item 项
  326. * @param by 要增加几(大于0)
  327. * @return
  328. */
  329. public double hincr(String key, String item, double by) {
  330. return redisTemplate.opsForHash().increment(key, item, by);
  331. }
  332. /**
  333. * hash递减
  334. *
  335. * @param key 键
  336. * @param item 项
  337. * @param by 要减少记(小于0)
  338. * @return
  339. */
  340. public double hdecr(String key, String item, double by) {
  341. return redisTemplate.opsForHash().increment(key, item, -by);
  342. }
  343. // ===============================Set=================================
  344. /**
  345. * 根据key获取Set中的所有值
  346. *
  347. * @param key 键
  348. * @return
  349. */
  350. public Set<Object> sGet(String key) {
  351. try {
  352. return redisTemplate.opsForSet().members(key);
  353. } catch (Exception e) {
  354. log.error(e.getMessage());
  355. throw BusinessException.create(GET_ERROR_MESSAGE);
  356. }
  357. }
  358. /**
  359. * 根据value从一个set中查询,是否存在
  360. *
  361. * @param key 键
  362. * @param value 值
  363. * @return true 存在 false不存在
  364. */
  365. public boolean sHasKey(String key, Object value) {
  366. try {
  367. return redisTemplate.opsForSet().isMember(key, value);
  368. } catch (Exception e) {
  369. log.error(e.getMessage());
  370. throw BusinessException.create(GET_ERROR_MESSAGE);
  371. }
  372. }
  373. /**
  374. * 将数据放入set缓存
  375. *
  376. * @param key 键
  377. * @param values 值 可以是多个
  378. * @return 成功个数
  379. */
  380. public long sSet(String key, Object... values) {
  381. try {
  382. return redisTemplate.opsForSet().add(key, values);
  383. } catch (Exception e) {
  384. log.error(e.getMessage());
  385. throw BusinessException.create(SET_ERROR_MESSAGE);
  386. }
  387. }
  388. /**
  389. * 将set数据放入缓存
  390. *
  391. * @param key 键
  392. * @param time 时间(秒)
  393. * @param values 值 可以是多个
  394. * @return 成功个数
  395. */
  396. public long sSetAndTime(String key, long time, Object... values) {
  397. try {
  398. Long count = redisTemplate.opsForSet().add(key, values);
  399. if (time > 0) {
  400. expire(key, time);
  401. }
  402. return count;
  403. } catch (Exception e) {
  404. log.error(e.getMessage());
  405. throw BusinessException.create(SET_ERROR_MESSAGE);
  406. }
  407. }
  408. /**
  409. * 获取set缓存的长度
  410. *
  411. * @param key 键
  412. * @return
  413. */
  414. public long sGetSetSize(String key) {
  415. try {
  416. return redisTemplate.opsForSet().size(key);
  417. } catch (Exception e) {
  418. log.error(e.getMessage());
  419. throw BusinessException.create(GET_ERROR_MESSAGE);
  420. }
  421. }
  422. /**
  423. * 移除值为value的
  424. *
  425. * @param key 键
  426. * @param values 值 可以是多个
  427. * @return 移除的个数
  428. */
  429. public long setRemove(String key, Object... values) {
  430. try {
  431. Long count = redisTemplate.opsForSet().remove(key, values);
  432. return count;
  433. } catch (Exception e) {
  434. log.error(e.getMessage());
  435. throw BusinessException.create(DELETE_ERROR_MESSAGE);
  436. }
  437. }
  438. // ===============================list=================================
  439. /**
  440. * 获取list缓存的内容
  441. *
  442. * @param key 键
  443. * @param start 开始
  444. * @param end 结束 0 到 -1代表所有值
  445. * @return
  446. */
  447. public List<Object> lGet(String key, long start, long end) {
  448. try {
  449. return redisTemplate.opsForList().range(key, start, end);
  450. } catch (Exception e) {
  451. log.error(e.getMessage());
  452. throw BusinessException.create(GET_ERROR_MESSAGE);
  453. }
  454. }
  455. /**
  456. * 获取list缓存的长度
  457. *
  458. * @param key 键
  459. * @return
  460. */
  461. public long lGetListSize(String key) {
  462. try {
  463. return redisTemplate.opsForList().size(key);
  464. } catch (Exception e) {
  465. log.error(e.getMessage());
  466. throw BusinessException.create(GET_ERROR_MESSAGE);
  467. }
  468. }
  469. /**
  470. * 通过索引 获取list中的值
  471. *
  472. * @param key 键
  473. * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
  474. * @return
  475. */
  476. public Object lGetIndex(String key, long index) {
  477. try {
  478. return redisTemplate.opsForList().index(key, index);
  479. } catch (Exception e) {
  480. log.error(e.getMessage());
  481. throw BusinessException.create(GET_ERROR_MESSAGE);
  482. }
  483. }
  484. /**
  485. * 将list放入缓存
  486. *
  487. * @param key 键
  488. * @param value 值
  489. * @return
  490. */
  491. public boolean lSet(String key, Object value) {
  492. try {
  493. redisTemplate.opsForList().rightPush(key, value);
  494. return true;
  495. } catch (Exception e) {
  496. log.error(e.getMessage());
  497. throw BusinessException.create(SET_ERROR_MESSAGE);
  498. }
  499. }
  500. /**
  501. * 将list放入缓存
  502. *
  503. * @param key 键
  504. * @param value 值
  505. * @param time 时间(秒)
  506. * @return
  507. */
  508. public boolean lSet(String key, Object value, long time) {
  509. try {
  510. redisTemplate.opsForList().rightPush(key, value);
  511. if (time > 0) {
  512. expire(key, time);
  513. }
  514. return true;
  515. } catch (Exception e) {
  516. log.error(e.getMessage());
  517. throw BusinessException.create(SET_ERROR_MESSAGE);
  518. }
  519. }
  520. /**
  521. * 将list放入缓存
  522. *
  523. * @param key 键
  524. * @param value 值
  525. * @return
  526. */
  527. public boolean lSet(String key, List<Object> value) {
  528. try {
  529. redisTemplate.opsForList().rightPushAll(key, value);
  530. return true;
  531. } catch (Exception e) {
  532. log.error(e.getMessage());
  533. throw BusinessException.create(SET_ERROR_MESSAGE);
  534. }
  535. }
  536. /**
  537. * 将list放入缓存
  538. *
  539. * @param key 键
  540. * @param value 值
  541. * @param time 时间(秒)
  542. * @return
  543. */
  544. public boolean lSet(String key, List<Object> value, long time) {
  545. try {
  546. redisTemplate.opsForList().rightPushAll(key, value);
  547. if (time > 0) {
  548. expire(key, time);
  549. }
  550. return true;
  551. } catch (Exception e) {
  552. log.error(e.getMessage());
  553. throw BusinessException.create(SET_ERROR_MESSAGE);
  554. }
  555. }
  556. /**
  557. * 根据索引修改list中的某条数据
  558. *
  559. * @param key 键
  560. * @param index 索引
  561. * @param value 值
  562. * @return
  563. */
  564. public boolean lUpdateIndex(String key, long index, Object value) {
  565. try {
  566. redisTemplate.opsForList().set(key, index, value);
  567. return true;
  568. } catch (Exception e) {
  569. log.error(e.getMessage());
  570. throw BusinessException.create(SET_ERROR_MESSAGE);
  571. }
  572. }
  573. /**
  574. * 移除N个值为value
  575. *
  576. * @param key 键
  577. * @param count 移除多少个
  578. * @param value 值
  579. * @return 移除的个数
  580. */
  581. public long lRemove(String key, long count, Object value) {
  582. try {
  583. Long remove = redisTemplate.opsForList().remove(key, count, value);
  584. return remove;
  585. } catch (Exception e) {
  586. log.error(e.getMessage());
  587. throw BusinessException.create(DELETE_ERROR_MESSAGE);
  588. }
  589. }
  590. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/234434
推荐阅读
相关标签
  

闽ICP备14008679号