From 05a3ce459606433d544e598d5bdbd5eb0e5508a6 Mon Sep 17 00:00:00 2001 From: huangfeng Date: Wed, 30 Apr 2025 10:40:00 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BD=BF=E7=94=A8redis=E4=BF=9D?= =?UTF-8?q?=E5=AD=98token=EF=BC=8C=E4=BD=BF=E7=94=A8=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E5=BB=B6=E6=9C=9F=EF=BC=8C7=E5=A4=A9=E4=B8=8D=E7=94=A8?= =?UTF-8?q?=E5=A4=B1=E6=95=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../XymanagerAdminApplication.java | 2 +- .../src/main/resources/application-test.yml | 5 +- xymanager_common/pom.xml | 23 ++++ .../shxy/xymanager_common/util/RedisUtil.java | 105 ++++++++++++++++++ .../shxy/xymanager_common/util/TokenUtil.java | 31 ++++++ .../filter/UserInfoFilter.java | 2 +- .../impl/UserServiceImpl.java | 2 +- 7 files changed, 166 insertions(+), 4 deletions(-) create mode 100644 xymanager_common/src/main/java/com/shxy/xymanager_common/util/RedisUtil.java diff --git a/xymanager_admin/src/main/java/com/shxy/xymanager_admin/XymanagerAdminApplication.java b/xymanager_admin/src/main/java/com/shxy/xymanager_admin/XymanagerAdminApplication.java index d212afa..6f40643 100644 --- a/xymanager_admin/src/main/java/com/shxy/xymanager_admin/XymanagerAdminApplication.java +++ b/xymanager_admin/src/main/java/com/shxy/xymanager_admin/XymanagerAdminApplication.java @@ -21,7 +21,7 @@ import org.springframework.scheduling.annotation.EnableScheduling; @EnableAspectJAutoProxy(exposeProxy = true) @Slf4j @EnableConfigurationProperties -@ComponentScan(basePackages = {"com.shxy"}) +@ComponentScan(basePackages = {"com.shxy","org.springframework.data.redis"}) @EnableCaching @EnableAsync @EnableScheduling diff --git a/xymanager_admin/src/main/resources/application-test.yml b/xymanager_admin/src/main/resources/application-test.yml index 87a31e1..db7d175 100644 --- a/xymanager_admin/src/main/resources/application-test.yml +++ b/xymanager_admin/src/main/resources/application-test.yml @@ -1,11 +1,14 @@ # Spring配置 spring: + redis: + host: 192.168.1.190 + port: 6379 jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 datasource: driver-class-name: com.mysql.cj.jdbc.Driver - url: jdbc:mysql://192.168.1.190:3306/xymp?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + url: jdbc:mysql://192.168.1.190:3306/xymp_chenxi?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 username: root password: 123456 type: com.alibaba.druid.pool.DruidDataSource diff --git a/xymanager_common/pom.xml b/xymanager_common/pom.xml index 95fac1b..8edc689 100644 --- a/xymanager_common/pom.xml +++ b/xymanager_common/pom.xml @@ -43,6 +43,29 @@ javax.servlet-api + + org.springframework.boot + spring-boot-starter-data-redis + + + + io.lettuce + lettuce-core + + + + + + redis.clients + jedis + 3.6.3 + + + org.apache.commons + commons-pool2 + + + org.projectlombok diff --git a/xymanager_common/src/main/java/com/shxy/xymanager_common/util/RedisUtil.java b/xymanager_common/src/main/java/com/shxy/xymanager_common/util/RedisUtil.java new file mode 100644 index 0000000..bbcbfa9 --- /dev/null +++ b/xymanager_common/src/main/java/com/shxy/xymanager_common/util/RedisUtil.java @@ -0,0 +1,105 @@ +package com.shxy.xymanager_common.util; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.util.CollectionUtils; + +import java.util.Collection; +import java.util.Date; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +@Configuration +@Slf4j +public class RedisUtil { + @Autowired + private StringRedisTemplate stringRedisTemplate; + + + public boolean getTodayLock(String name) { + String key = DateUtil.format(new Date(), "yyyy-MM-dd") + name; + return stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 3, TimeUnit.MINUTES); + } + + /** + * 判断key是否存在 + * + * @param key 键 + * @return true 存在 false不存在 + */ + public boolean hasKey(String key) { + try { + return stringRedisTemplate.hasKey(key); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + + /** + * 删除缓存 + * + * @param collection 可以传一个值 或多个 + */ + public void del(Collection collection) { + if (!CollectionUtils.isEmpty(collection)) { + stringRedisTemplate.delete(collection); + } + } + + /** + * 获取指定key的值 + * + * @param key 键 + * @return true成功 false失败 + */ + public String get(String key) { + return stringRedisTemplate.opsForValue().get(key); + } + + /** + * 普通缓存放入 + * + * @param key 键 + * @param value 值 + * @return true成功 false失败 + */ + public boolean set(String key, String value) { + try { + stringRedisTemplate.opsForValue().set(key, value); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * 普通缓存放入并设置时间 + * + * @param key 键 + * @param value 值 + * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 + * @return true成功 false 失败 + */ + public boolean set(String key, String value, long time) { + try { + if (time > 0) { + stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); + } else { + set(key, value); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public Set keys(String s) { + return stringRedisTemplate.keys(s); + } +} diff --git a/xymanager_common/src/main/java/com/shxy/xymanager_common/util/TokenUtil.java b/xymanager_common/src/main/java/com/shxy/xymanager_common/util/TokenUtil.java index c8b6f6c..3bd6511 100644 --- a/xymanager_common/src/main/java/com/shxy/xymanager_common/util/TokenUtil.java +++ b/xymanager_common/src/main/java/com/shxy/xymanager_common/util/TokenUtil.java @@ -8,9 +8,11 @@ import io.jsonwebtoken.security.Keys; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import javax.annotation.Resource; import javax.crypto.SecretKey; import java.nio.charset.StandardCharsets; import java.util.Date; +import java.util.UUID; @Component public class TokenUtil { @@ -18,6 +20,9 @@ public class TokenUtil { @Autowired SecurityConfig config; + @Resource + RedisUtil redisUtil; + public String generateToken(Integer userId) { SecretKey key = Keys.hmacShaKeyFor(config.getJwtPwd().getBytes(StandardCharsets.UTF_8)); String uuid = UuidUtils.getUUID(); @@ -41,4 +46,30 @@ public class TokenUtil { String userId = claims.getSubject(); return userId; } + + public String generateToken2(Integer userId) { + String token = UUID.randomUUID().toString().replaceAll("-", ""); + String str = userId.toString() + "," + System.currentTimeMillis() / 1000; + redisUtil.set(token, str, config.getJwtExpiration()); + return token; + } + + public String getUserId2(String token) { + String userId = null; + try { + String str = redisUtil.get(token); + if (str != null) { + String[] strs = str.split(","); + long time = Long.parseLong(strs[1]); + long sec = System.currentTimeMillis() / 1000 - time; + if (sec < config.getJwtExpiration()) { + userId = strs[0]; + str = userId + "," + System.currentTimeMillis() / 1000; + redisUtil.set(token, str, config.getJwtExpiration()); + } + } + } catch (Exception ex) { + } + return userId; + } } diff --git a/xymanager_framework/src/main/java/com/shxy/xymanager_framework/filter/UserInfoFilter.java b/xymanager_framework/src/main/java/com/shxy/xymanager_framework/filter/UserInfoFilter.java index 83655a6..d1d2843 100644 --- a/xymanager_framework/src/main/java/com/shxy/xymanager_framework/filter/UserInfoFilter.java +++ b/xymanager_framework/src/main/java/com/shxy/xymanager_framework/filter/UserInfoFilter.java @@ -72,7 +72,7 @@ public class UserInfoFilter extends AbstractAuthorizationFilter { private boolean initContextHolders(HttpServletRequest request) { String token = request.getHeader(config.getJwtHeader()); if (!StringUtils.isBlank(token)) { - String userId = tokenUtil.getUserId(token); + String userId = tokenUtil.getUserId2(token); if (!StringUtils.isBlank(userId)) { SysUser user = userService.selectUserById(Integer.parseInt(userId)); UserContextHolder.setCurrentUserInfo(user); diff --git a/xymanager_service/src/main/java/com/shxy/xymanager_service/impl/UserServiceImpl.java b/xymanager_service/src/main/java/com/shxy/xymanager_service/impl/UserServiceImpl.java index 5232ae8..77bc670 100644 --- a/xymanager_service/src/main/java/com/shxy/xymanager_service/impl/UserServiceImpl.java +++ b/xymanager_service/src/main/java/com/shxy/xymanager_service/impl/UserServiceImpl.java @@ -61,7 +61,7 @@ public class UserServiceImpl implements UserService { if (!sysUser.getPassword().equals(pwd)) { throw new ApiException(HttpStatusCode.ERROR, "用户或密码不正确"); } - String token = tokenUtil.generateToken(user.getUid()); + String token = tokenUtil.generateToken2(user.getUid()); user.setToken(token); if (SUPER_ADMIN != user.getRole()) {