feat: 使用redis保存token,使用自动延期,7天不用失效

dev
huangfeng 2 months ago
parent b432c7e148
commit 05a3ce4596

@ -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

@ -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

@ -43,6 +43,29 @@
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<!-- 排除 Lettuce -->
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 添加 Jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.6.3</version> <!-- 可选,建议与 Spring Boot 2.x 兼容的最新版本 -->
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>

@ -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<String> 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 () time0 time0
* @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<String> keys(String s) {
return stringRedisTemplate.keys(s);
}
}

@ -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;
}
}

@ -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);

@ -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()) {

Loading…
Cancel
Save