huliguo
2025-04-30 16427ab3e7335fb6242699ee4afb9881dfd13439
过期token定时清理
3个文件已修改
36 ■■■■■ 已修改文件
src/main/java/com/cl/CanLianScreenApplication.java 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/cl/service/impl/TokenBlacklistService.java 30 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/resources/mapper/InstitutionMapper.xml 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/cl/CanLianScreenApplication.java
@@ -4,10 +4,12 @@
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableSwagger2
@SpringBootApplication
@EnableScheduling
public class CanLianScreenApplication {
    public static void main(String[] args)
    {
src/main/java/com/cl/service/impl/TokenBlacklistService.java
@@ -1,15 +1,22 @@
package com.cl.service.impl;
import com.cl.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class TokenBlacklistService {
    // 使用ConcurrentHashMap或Redis存储黑名单
    private final Set<String> blacklist = Collections.newSetFromMap(new ConcurrentHashMap<>());
@@ -22,4 +29,27 @@
        return blacklist.contains(token);
    }
    /**
     * 定时清理过期令牌(每2小时执行一次)
     */
    @Scheduled(fixedRate = 2, timeUnit = TimeUnit.HOURS)
    public void cleanupExpiredTokens() {
        log.info("开始清理过期token");
        blacklist.removeIf(this::isTokenExpired);
    }
    /**
     * 检查JWT Token是否过期
     * @param token JWT Token字符串
     * @return true-已过期,false-未过期
     */
    public boolean isTokenExpired(String token) {
        try {
            Claims claims = JwtUtil.parseJWT(token);
            return claims.getExpiration().before(new Date());
        } catch (Exception e) {
            // 如果解析过程中出现异常(如Token无效、已过期等),视为已过期
            return true;
        }
    }
}
src/main/resources/mapper/InstitutionMapper.xml
@@ -13,8 +13,8 @@
        <if test="null!=county and county!=0">
            and county=#{county}
        </if>
        <if test="null!=phone and ''!=phone">
            and phone like concat('%',#{phone},'%')
        <if test="null!=name and ''!=name">
            and name like concat('%',#{name},'%')
        </if>
        order by id desc