update 配置统一提取为 properties 配置类

This commit is contained in:
疯狂的狮子li 2021-05-17 13:39:59 +08:00
parent 0fc1f4e10e
commit 5e32b5f0bf
13 changed files with 270 additions and 183 deletions

View File

@ -13,8 +13,8 @@ import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.constant.Constants; import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache; import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.framework.config.properties.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@ -42,18 +42,8 @@ public class CaptchaController {
@Autowired @Autowired
private RedisCache redisCache; private RedisCache redisCache;
// 验证码类型 @Autowired
@Value("${captcha.captchaType}") private CaptchaProperties captchaProperties;
private String captchaType;
// 验证码类别
@Value("${captcha.captchaCategory}")
private String captchaCategory;
// 数字验证码位数
@Value("${captcha.captchaNumberLength}")
private int numberLength;
// 字符验证码长度
@Value("${captcha.captchaCharLength}")
private int charLength;
/** /**
* 生成验证码 * 生成验证码
@ -67,17 +57,17 @@ public class CaptchaController {
// 生成验证码 // 生成验证码
CodeGenerator codeGenerator; CodeGenerator codeGenerator;
AbstractCaptcha captcha; AbstractCaptcha captcha;
switch (captchaType) { switch (captchaProperties.getType()) {
case "math": case "math":
codeGenerator = new MathGenerator(numberLength); codeGenerator = new MathGenerator(captchaProperties.getNumberLength());
break; break;
case "char": case "char":
codeGenerator = new RandomGenerator(charLength); codeGenerator = new RandomGenerator(captchaProperties.getCharLength());
break; break;
default: default:
throw new IllegalArgumentException("验证码类型异常"); throw new IllegalArgumentException("验证码类型异常");
} }
switch (captchaCategory) { switch (captchaProperties.getCategory()) {
case "line": case "line":
captcha = lineCaptcha; captcha = lineCaptcha;
break; break;
@ -92,9 +82,9 @@ public class CaptchaController {
} }
captcha.setGenerator(codeGenerator); captcha.setGenerator(codeGenerator);
captcha.createCode(); captcha.createCode();
if ("math".equals(captchaType)) { if ("math".equals(captchaProperties.getType())) {
code = getCodeResult(captcha.getCode()); code = getCodeResult(captcha.getCode());
} else if ("char".equals(captchaType)) { } else if ("char".equals(captchaProperties.getType())) {
code = captcha.getCode(); code = captcha.getCode();
} }
redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES); redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
@ -105,6 +95,7 @@ public class CaptchaController {
} }
private String getCodeResult(String capStr) { private String getCodeResult(String capStr) {
int numberLength = captchaProperties.getNumberLength();
int a = Convert.toInt(StrUtil.sub(capStr, 0, numberLength).trim()); int a = Convert.toInt(StrUtil.sub(capStr, 0, numberLength).trim());
char operator = capStr.charAt(numberLength); char operator = capStr.charAt(numberLength);
int b = Convert.toInt(StrUtil.sub(capStr, numberLength + 1, numberLength + 1 + numberLength).trim()); int b = Convert.toInt(StrUtil.sub(capStr, numberLength + 1, numberLength + 1 + numberLength).trim());

View File

@ -15,13 +15,13 @@ ruoyi:
captcha: captcha:
# 验证码类型 math 数组计算 char 字符验证 # 验证码类型 math 数组计算 char 字符验证
captchaType: math type: math
# line 线段干扰 circle 圆圈干扰 shear 扭曲干扰 # line 线段干扰 circle 圆圈干扰 shear 扭曲干扰
captchaCategory: circle category: circle
# 数字验证码位数 # 数字验证码位数
captchaNumberLength: 1 numberLength: 1
# 字符验证码长度 # 字符验证码长度
captchaCharLength: 4 charLength: 4
# 开发环境配置 # 开发环境配置
server: server:
@ -187,8 +187,6 @@ mybatis-plus:
swagger: swagger:
# 是否开启swagger # 是否开启swagger
enabled: true enabled: true
# 请求前缀
pathMapping: /dev-api
# 标题 # 标题
title: '标题RuoYi-Vue-Plus后台管理系统_接口文档' title: '标题RuoYi-Vue-Plus后台管理系统_接口文档'
# 描述 # 描述
@ -206,7 +204,7 @@ xss:
urlPatterns: /system/*,/monitor/*,/tool/* urlPatterns: /system/*,/monitor/*,/tool/*
# 全局线程池相关配置 # 全局线程池相关配置
threadPoolConfig: thread-pool:
# 是否开启线程池 # 是否开启线程池
enabled: false enabled: false
# 核心线程池大小 # 核心线程池大小

View File

@ -145,6 +145,11 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId> <artifactId>spring-boot-starter-actuator</artifactId>
</dependency> </dependency>
<!-- 自动生成YML配置关联JSON文件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
</dependencies> </dependencies>

View File

@ -3,7 +3,8 @@ package com.ruoyi.framework.config;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.filter.RepeatableFilter; import com.ruoyi.common.filter.RepeatableFilter;
import com.ruoyi.common.filter.XssFilter; import com.ruoyi.common.filter.XssFilter;
import org.springframework.beans.factory.annotation.Value; import com.ruoyi.framework.config.properties.XssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -15,41 +16,33 @@ import java.util.Map;
/** /**
* Filter配置 * Filter配置
* *
* @author ruoyi * @author Lion Li
*/ */
@Configuration @Configuration
public class FilterConfig public class FilterConfig {
{
@Value("${xss.enabled}")
private String enabled;
@Value("${xss.excludes}") @Autowired
private String excludes; private XssProperties xssProperties;
@Value("${xss.urlPatterns}") @SuppressWarnings({"rawtypes", "unchecked"})
private String urlPatterns;
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean @Bean
public FilterRegistrationBean xssFilterRegistration() public FilterRegistrationBean xssFilterRegistration() {
{
FilterRegistrationBean registration = new FilterRegistrationBean(); FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setDispatcherTypes(DispatcherType.REQUEST); registration.setDispatcherTypes(DispatcherType.REQUEST);
registration.setFilter(new XssFilter()); registration.setFilter(new XssFilter());
registration.addUrlPatterns(StrUtil.split(urlPatterns, ",")); registration.addUrlPatterns(StrUtil.split(xssProperties.getUrlPatterns(), ","));
registration.setName("xssFilter"); registration.setName("xssFilter");
registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE); registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
Map<String, String> initParameters = new HashMap<String, String>(); Map<String, String> initParameters = new HashMap<String, String>();
initParameters.put("excludes", excludes); initParameters.put("excludes", xssProperties.getExcludes());
initParameters.put("enabled", enabled); initParameters.put("enabled", xssProperties.getEnabled());
registration.setInitParameters(initParameters); registration.setInitParameters(initParameters);
return registration; return registration;
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
@Bean @Bean
public FilterRegistrationBean someFilterRegistration() public FilterRegistrationBean someFilterRegistration() {
{
FilterRegistrationBean registration = new FilterRegistrationBean(); FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new RepeatableFilter()); registration.setFilter(new RepeatableFilter());
registration.addUrlPatterns("/*"); registration.addUrlPatterns("/*");

View File

@ -1,4 +1,4 @@
package com.ruoyi.web.core.config; package com.ruoyi.framework.config;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.ruoyi.common.config.RuoYiConfig; import com.ruoyi.common.config.RuoYiConfig;
@ -38,12 +38,6 @@ public class SwaggerConfig {
@Autowired @Autowired
private RuoYiConfig ruoyiConfig; private RuoYiConfig ruoyiConfig;
/**
* 设置请求的统一前缀
*/
@Value("${swagger.pathMapping}")
private String pathMapping;
/** /**
* 标题 * 标题
*/ */

View File

@ -1,8 +1,9 @@
package com.ruoyi.framework.config; package com.ruoyi.framework.config;
import com.ruoyi.common.utils.Threads; import com.ruoyi.common.utils.Threads;
import com.ruoyi.framework.config.properties.ThreadPoolProperties;
import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -21,43 +22,31 @@ import java.util.concurrent.ThreadPoolExecutor;
@Configuration @Configuration
public class ThreadPoolConfig { public class ThreadPoolConfig {
// 核心线程池大小 @Autowired
@Value("${threadPoolConfig.corePoolSize}") private ThreadPoolProperties threadPoolProperties;
private int corePoolSize;
// 最大可创建的线程数
@Value("${threadPoolConfig.maxPoolSize}")
private int maxPoolSize;
// 队列最大长度
@Value("${threadPoolConfig.queueCapacity}")
private int queueCapacity;
// 线程池维护线程所允许的空闲时间
@Value("${threadPoolConfig.keepAliveSeconds}")
private int keepAliveSeconds;
// 线程池对拒绝任务(无线程可用)的处理策略
@Value("${threadPoolConfig.rejectedExecutionHandler}")
private String rejectedExecutionHandler;
@Bean(name = "threadPoolTaskExecutor") @Bean(name = "threadPoolTaskExecutor")
@ConditionalOnProperty(prefix = "threadPoolTaskExecutor", name = "enabled", havingValue = "true") @ConditionalOnProperty(prefix = "threadPoolTaskExecutor", name = "enabled", havingValue = "true")
public ThreadPoolTaskExecutor threadPoolTaskExecutor() { public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setMaxPoolSize(maxPoolSize); executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
executor.setCorePoolSize(corePoolSize); executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
executor.setQueueCapacity(queueCapacity); executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
executor.setKeepAliveSeconds(keepAliveSeconds); executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
RejectedExecutionHandler handler; RejectedExecutionHandler handler;
if (rejectedExecutionHandler.equals("CallerRunsPolicy")) { switch (threadPoolProperties.getRejectedExecutionHandler()) {
handler = new ThreadPoolExecutor.CallerRunsPolicy(); case "CallerRunsPolicy":
} else if (rejectedExecutionHandler.equals("DiscardOldestPolicy")) { handler = new ThreadPoolExecutor.CallerRunsPolicy();
handler = new ThreadPoolExecutor.DiscardOldestPolicy(); break;
} else if (rejectedExecutionHandler.equals("DiscardPolicy")) { case "DiscardOldestPolicy":
handler = new ThreadPoolExecutor.DiscardPolicy(); handler = new ThreadPoolExecutor.DiscardOldestPolicy();
} else { break;
handler = new ThreadPoolExecutor.AbortPolicy(); case "DiscardPolicy":
handler = new ThreadPoolExecutor.DiscardPolicy();
break;
default:
handler = new ThreadPoolExecutor.AbortPolicy();
break;
} }
executor.setRejectedExecutionHandler(handler); executor.setRejectedExecutionHandler(handler);
return executor; return executor;
@ -68,7 +57,7 @@ public class ThreadPoolConfig {
*/ */
@Bean(name = "scheduledExecutorService") @Bean(name = "scheduledExecutorService")
protected ScheduledExecutorService scheduledExecutorService() { protected ScheduledExecutorService scheduledExecutorService() {
return new ScheduledThreadPoolExecutor(corePoolSize, return new ScheduledThreadPoolExecutor(threadPoolProperties.getCorePoolSize(),
new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()) { new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()) {
@Override @Override
protected void afterExecute(Runnable r, Throwable t) { protected void afterExecute(Runnable r, Throwable t) {

View File

@ -0,0 +1,24 @@
package com.ruoyi.framework.config.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 验证码 配置属性
*
* @author Lion Li
*/
@Data
@Component
@ConfigurationProperties(prefix = "captcha")
public class CaptchaProperties {
// 验证码类型
private String type;
// 验证码类别
private String category;
// 数字验证码位数
private Integer numberLength;
// 字符验证码长度
private Integer charLength;
}

View File

@ -1,76 +1,54 @@
package com.ruoyi.framework.config.properties; package com.ruoyi.framework.config.properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/** /**
* druid 配置属性 * druid 配置属性
* *
* @author ruoyi * @author Lion Li
*/ */
@Data
@Configuration @Configuration
public class DruidProperties @ConfigurationProperties(prefix = "spring.datasource.druid")
{ public class DruidProperties {
@Value("${spring.datasource.druid.initialSize}")
/** 初始连接数 */
private int initialSize; private int initialSize;
/** 最小连接池数量 */
@Value("${spring.datasource.druid.minIdle}")
private int minIdle; private int minIdle;
/** 最大连接池数量 */
@Value("${spring.datasource.druid.maxActive}")
private int maxActive; private int maxActive;
/** 配置获取连接等待超时的时间 */
@Value("${spring.datasource.druid.maxWait}")
private int maxWait; private int maxWait;
/** 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 */
@Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis; private int timeBetweenEvictionRunsMillis;
/** 配置一个连接在池中最小生存的时间,单位是毫秒 */
@Value("${spring.datasource.druid.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis; private int minEvictableIdleTimeMillis;
/** 配置一个连接在池中最大生存的时间,单位是毫秒 */
@Value("${spring.datasource.druid.maxEvictableIdleTimeMillis}")
private int maxEvictableIdleTimeMillis; private int maxEvictableIdleTimeMillis;
/** 配置检测连接是否有效 */
@Value("${spring.datasource.druid.validationQuery}")
private String validationQuery; private String validationQuery;
/** 初始连接数 */
@Value("${spring.datasource.druid.testWhileIdle}")
private boolean testWhileIdle; private boolean testWhileIdle;
/** 初始连接数 */
@Value("${spring.datasource.druid.testOnBorrow}")
private boolean testOnBorrow; private boolean testOnBorrow;
/** 初始连接数 */
@Value("${spring.datasource.druid.testOnReturn}")
private boolean testOnReturn; private boolean testOnReturn;
public DruidDataSource dataSource(DruidDataSource datasource) public DruidDataSource dataSource(DruidDataSource datasource) {
{
/** 配置初始化大小、最小、最大 */
datasource.setInitialSize(initialSize); datasource.setInitialSize(initialSize);
datasource.setMaxActive(maxActive); datasource.setMaxActive(maxActive);
datasource.setMinIdle(minIdle); datasource.setMinIdle(minIdle);
/** 配置获取连接等待超时的时间 */
datasource.setMaxWait(maxWait); datasource.setMaxWait(maxWait);
/** 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 */
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
/** 配置一个连接在池中最小、最大生存的时间,单位是毫秒 */
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis); datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis);
/**
* 用来检测连接是否有效的sql要求是一个查询语句常用select 'x'如果validationQuery为nulltestOnBorrowtestOnReturntestWhileIdle都不会起作用
*/
datasource.setValidationQuery(validationQuery); datasource.setValidationQuery(validationQuery);
/** 建议配置为true不影响性能并且保证安全性。申请连接的时候检测如果空闲时间大于timeBetweenEvictionRunsMillis执行validationQuery检测连接是否有效。 */
datasource.setTestWhileIdle(testWhileIdle); datasource.setTestWhileIdle(testWhileIdle);
/** 申请连接时执行validationQuery检测连接是否有效做了这个配置会降低性能。 */
datasource.setTestOnBorrow(testOnBorrow); datasource.setTestOnBorrow(testOnBorrow);
/** 归还连接时执行validationQuery检测连接是否有效做了这个配置会降低性能。 */
datasource.setTestOnReturn(testOnReturn); datasource.setTestOnReturn(testOnReturn);
return datasource; return datasource;
} }

View File

@ -0,0 +1,36 @@
package com.ruoyi.framework.config.properties;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 验证码 配置属性
*
* @author Lion Li
*/
@Data
@Component
@ConfigurationProperties(prefix = "swagger")
public class SwaggerProperties {
/**
* 验证码类型
*/
private Boolean enabled;
/**
* 验证码类别
*/
private String title;
/**
* 数字验证码位数
*/
private String description;
/**
* 字符验证码长度
*/
private String version;
}

View File

@ -0,0 +1,47 @@
package com.ruoyi.framework.config.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 验证码 配置属性
*
* @author Lion Li
*/
@Data
@Component
@ConfigurationProperties(prefix = "thread-pool")
public class ThreadPoolProperties {
/**
* 是否开启线程池
*/
private boolean enabled;
/**
* 核心线程池大小
*/
private int corePoolSize;
/**
* 最大可创建的线程数
*/
private int maxPoolSize;
/**
* 队列最大长度
*/
private int queueCapacity;
/**
* 线程池维护线程所允许的空闲时间
*/
private int keepAliveSeconds;
/**
* 线程池对拒绝任务(无线程可用)的处理策略
*/
private String rejectedExecutionHandler;
}

View File

@ -0,0 +1,26 @@
package com.ruoyi.framework.config.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "token")
public class TokenProperties {
/**
* 令牌自定义标识
*/
private String header;
/**
* 令牌秘钥
*/
private String secret;
/**
* 令牌有效期默认30分钟
*/
private int expireTime;
}

View File

@ -0,0 +1,32 @@
package com.ruoyi.framework.config.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 验证码 配置属性
*
* @author Lion Li
*/
@Data
@Component
@ConfigurationProperties(prefix = "xss")
public class XssProperties {
/**
* 过滤开关
*/
private String enabled;
/**
* 排除链接多个用逗号分隔
*/
private String excludes;
/**
* 匹配链接
*/
private String urlPatterns;
}

View File

@ -10,11 +10,11 @@ import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils; import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ip.AddressUtils; import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils; import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.config.properties.TokenProperties;
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -25,22 +25,10 @@ import java.util.concurrent.TimeUnit;
/** /**
* token验证处理 * token验证处理
* *
* @author ruoyi * @author Lion Li
*/ */
@Component @Component
public class TokenService public class TokenService {
{
// 令牌自定义标识
@Value("${token.header}")
private String header;
// 令牌秘钥
@Value("${token.secret}")
private String secret;
// 令牌有效期默认30分钟
@Value("${token.expireTime}")
private int expireTime;
protected static final long MILLIS_SECOND = 1000; protected static final long MILLIS_SECOND = 1000;
@ -51,17 +39,18 @@ public class TokenService
@Autowired @Autowired
private RedisCache redisCache; private RedisCache redisCache;
@Autowired
private TokenProperties tokenProperties;
/** /**
* 获取用户身份信息 * 获取用户身份信息
* *
* @return 用户信息 * @return 用户信息
*/ */
public LoginUser getLoginUser(HttpServletRequest request) public LoginUser getLoginUser(HttpServletRequest request) {
{
// 获取请求携带的令牌 // 获取请求携带的令牌
String token = getToken(request); String token = getToken(request);
if (Validator.isNotEmpty(token)) if (Validator.isNotEmpty(token)) {
{
Claims claims = parseToken(token); Claims claims = parseToken(token);
// 解析对应的权限以及用户信息 // 解析对应的权限以及用户信息
String uuid = (String) claims.get(Constants.LOGIN_USER_KEY); String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
@ -75,10 +64,8 @@ public class TokenService
/** /**
* 设置用户身份信息 * 设置用户身份信息
*/ */
public void setLoginUser(LoginUser loginUser) public void setLoginUser(LoginUser loginUser) {
{ if (Validator.isNotNull(loginUser) && Validator.isNotEmpty(loginUser.getToken())) {
if (Validator.isNotNull(loginUser) && Validator.isNotEmpty(loginUser.getToken()))
{
refreshToken(loginUser); refreshToken(loginUser);
} }
} }
@ -86,10 +73,8 @@ public class TokenService
/** /**
* 删除用户身份信息 * 删除用户身份信息
*/ */
public void delLoginUser(String token) public void delLoginUser(String token) {
{ if (Validator.isNotEmpty(token)) {
if (Validator.isNotEmpty(token))
{
String userKey = getTokenKey(token); String userKey = getTokenKey(token);
redisCache.deleteObject(userKey); redisCache.deleteObject(userKey);
} }
@ -101,8 +86,7 @@ public class TokenService
* @param loginUser 用户信息 * @param loginUser 用户信息
* @return 令牌 * @return 令牌
*/ */
public String createToken(LoginUser loginUser) public String createToken(LoginUser loginUser) {
{
String token = IdUtil.fastUUID(); String token = IdUtil.fastUUID();
loginUser.setToken(token); loginUser.setToken(token);
setUserAgent(loginUser); setUserAgent(loginUser);
@ -119,12 +103,10 @@ public class TokenService
* @param loginUser * @param loginUser
* @return 令牌 * @return 令牌
*/ */
public void verifyToken(LoginUser loginUser) public void verifyToken(LoginUser loginUser) {
{
long expireTime = loginUser.getExpireTime(); long expireTime = loginUser.getExpireTime();
long currentTime = System.currentTimeMillis(); long currentTime = System.currentTimeMillis();
if (expireTime - currentTime <= MILLIS_MINUTE_TEN) if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
{
refreshToken(loginUser); refreshToken(loginUser);
} }
} }
@ -134,13 +116,12 @@ public class TokenService
* *
* @param loginUser 登录信息 * @param loginUser 登录信息
*/ */
public void refreshToken(LoginUser loginUser) public void refreshToken(LoginUser loginUser) {
{
loginUser.setLoginTime(System.currentTimeMillis()); loginUser.setLoginTime(System.currentTimeMillis());
loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE); loginUser.setExpireTime(loginUser.getLoginTime() + tokenProperties.getExpireTime() * MILLIS_MINUTE);
// 根据uuid将loginUser缓存 // 根据uuid将loginUser缓存
String userKey = getTokenKey(loginUser.getToken()); String userKey = getTokenKey(loginUser.getToken());
redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES); redisCache.setCacheObject(userKey, loginUser, tokenProperties.getExpireTime(), TimeUnit.MINUTES);
} }
/** /**
@ -148,8 +129,7 @@ public class TokenService
* *
* @param loginUser 登录信息 * @param loginUser 登录信息
*/ */
public void setUserAgent(LoginUser loginUser) public void setUserAgent(LoginUser loginUser) {
{
UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent")); UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
String ip = IpUtils.getIpAddr(ServletUtils.getRequest()); String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
loginUser.setIpaddr(ip); loginUser.setIpaddr(ip);
@ -164,11 +144,10 @@ public class TokenService
* @param claims 数据声明 * @param claims 数据声明
* @return 令牌 * @return 令牌
*/ */
private String createToken(Map<String, Object> claims) private String createToken(Map<String, Object> claims) {
{
String token = Jwts.builder() String token = Jwts.builder()
.setClaims(claims) .setClaims(claims)
.signWith(SignatureAlgorithm.HS512, secret).compact(); .signWith(SignatureAlgorithm.HS512, tokenProperties.getSecret()).compact();
return token; return token;
} }
@ -178,10 +157,9 @@ public class TokenService
* @param token 令牌 * @param token 令牌
* @return 数据声明 * @return 数据声明
*/ */
private Claims parseToken(String token) private Claims parseToken(String token) {
{
return Jwts.parser() return Jwts.parser()
.setSigningKey(secret) .setSigningKey(tokenProperties.getSecret())
.parseClaimsJws(token) .parseClaimsJws(token)
.getBody(); .getBody();
} }
@ -192,8 +170,7 @@ public class TokenService
* @param token 令牌 * @param token 令牌
* @return 用户名 * @return 用户名
*/ */
public String getUsernameFromToken(String token) public String getUsernameFromToken(String token) {
{
Claims claims = parseToken(token); Claims claims = parseToken(token);
return claims.getSubject(); return claims.getSubject();
} }
@ -204,18 +181,15 @@ public class TokenService
* @param request * @param request
* @return token * @return token
*/ */
private String getToken(HttpServletRequest request) private String getToken(HttpServletRequest request) {
{ String token = request.getHeader(tokenProperties.getHeader());
String token = request.getHeader(header); if (Validator.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
if (Validator.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
{
token = token.replace(Constants.TOKEN_PREFIX, ""); token = token.replace(Constants.TOKEN_PREFIX, "");
} }
return token; return token;
} }
private String getTokenKey(String uuid) private String getTokenKey(String uuid) {
{
return Constants.LOGIN_TOKEN_KEY + uuid; return Constants.LOGIN_TOKEN_KEY + uuid;
} }
} }