修改ttl 失效问题

This commit is contained in:
冷冷 2018-04-12 17:12:13 +08:00
parent bf5dd6f350
commit 40f41a0fe3
7 changed files with 30 additions and 100 deletions

View File

@ -17,14 +17,9 @@
<h2 align="center">Supporting pig group</h2> <h2 align="center">Supporting pig group</h2>
### 前端解决方案 ### 项目官网
https://gitee.com/smallweigit/avue
### 视频教程 文档、视频https://pig4cloud.com/
https://www.bilibili.com/video/av20229859/
### 使用文档
[pig开发文档V1.0](https://www.kancloud.cn/lengleng/pig-guide/550709)
### 分支介绍 ### 分支介绍

View File

@ -2,16 +2,12 @@ package com.github.pig.common.bean.aop;
import com.github.pig.common.constant.SecurityConstants; import com.github.pig.common.constant.SecurityConstants;
import com.github.pig.common.util.UserUtils; import com.github.pig.common.util.UserUtils;
import com.github.pig.common.vo.UserVO; import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.lang.StringUtils; import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
@ -25,13 +21,10 @@ import java.util.Arrays;
* Controller 增强 * Controller 增强
*/ */
@Slf4j
@Aspect @Aspect
@Component @Component
public class ControllerAop { public class ControllerAop {
private static final Logger logger = LoggerFactory.getLogger(ControllerAop.class);
@Autowired
private CacheManager cacheManager;
@Pointcut("execution(public com.github.pig.common.util.R *(..))") @Pointcut("execution(public com.github.pig.common.util.R *(..))")
public void pointCutR() { public void pointCutR() {
} }
@ -69,39 +62,28 @@ public class ControllerAop {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest(); HttpServletRequest request = attributes.getRequest();
String token = UserUtils.getToken(request); String username = request.getHeader(SecurityConstants.USER_HEADER);
UserVO userVo = null; if (StrUtil.isNotBlank(username)){
if (StringUtils.isNotEmpty(token)) { log.info("Controller AOP get username:{}", username);
userVo = cacheManager.getCache(SecurityConstants.TOKEN_USER_DETAIL).get(token, UserVO.class);
}
String username;
if (userVo == null) {
username = UserUtils.getUserName(request);
if (StringUtils.isNotEmpty(username)) {
UserUtils.setUser(username); UserUtils.setUser(username);
} }
} else {
username = userVo.getUsername();
UserUtils.setUser(username);
}
logger.info("Controller AOP get username:{}", username);
logger.info("URL : " + request.getRequestURL().toString()); log.info("URL : " + request.getRequestURL().toString());
logger.info("HTTP_METHOD : " + request.getMethod()); log.info("HTTP_METHOD : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr()); log.info("IP : " + request.getRemoteAddr());
logger.info("CLASS_METHOD : " + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName()); log.info("CLASS_METHOD : " + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
logger.info("ARGS : " + Arrays.toString(pjp.getArgs())); log.info("ARGS : " + Arrays.toString(pjp.getArgs()));
Object result; Object result;
try { try {
result = pjp.proceed(); result = pjp.proceed();
logger.info(pjp.getSignature() + "use time:" + (System.currentTimeMillis() - startTime)); log.info(pjp.getSignature() + "use time:" + (System.currentTimeMillis() - startTime));
} catch (Throwable e) { } catch (Throwable e) {
logger.error("异常信息:", e); log.error("异常信息:", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} finally { } finally {
if (StringUtils.isNotEmpty(username)) { if (StrUtil.isNotEmpty(username)) {
UserUtils.clearAllUserInfo(); UserUtils.clearAllUserInfo();
} }
} }

View File

@ -56,6 +56,8 @@ public class TokenArgumentResolver implements HandlerMethodArgumentResolver {
if (StrUtil.isBlank(username) || StrUtil.isBlank(roles)) { if (StrUtil.isBlank(username) || StrUtil.isBlank(roles)) {
log.warn("resolveArgument error username or role is empty"); log.warn("resolveArgument error username or role is empty");
return null; return null;
} else {
log.info("resolveArgument username :{} roles:{}", username, roles);
} }
UserVO userVO = new UserVO(); UserVO userVO = new UserVO();
userVO.setUsername(username); userVO.setUsername(username);

View File

@ -24,55 +24,6 @@ public class UserUtils {
private static final ThreadLocal<String> THREAD_LOCAL_USER = new TransmittableThreadLocal<>(); private static final ThreadLocal<String> THREAD_LOCAL_USER = new TransmittableThreadLocal<>();
private static final String KEY_USER = "user"; private static final String KEY_USER = "user";
/**
* 根据用户请求中的token 获取用户名
*
* @param request Request
* @return username
*/
public static String getUserName(HttpServletRequest request) {
String username = "";
String authorization = request.getHeader(CommonConstant.REQ_HEADER);
if (StringUtils.isEmpty(authorization)) {
return username;
}
String token = StringUtils.substringAfter(authorization, CommonConstant.TOKEN_SPLIT);
if (StringUtils.isEmpty(token)) {
return username;
}
String key = Base64.getEncoder().encodeToString(CommonConstant.SIGN_KEY.getBytes());
try {
Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
username = claims.get("user_name").toString();
} catch (Exception ex) {
log.error("用户名解析异常,token:{},key:{}", token, key);
}
return username;
}
/**
* 通过token 获取用户名
*
* @param authorization token
* @return 用户名
*/
public static String getUserName(String authorization) {
String username = "";
String token = StringUtils.substringAfter(authorization, CommonConstant.TOKEN_SPLIT);
if (StringUtils.isEmpty(token)) {
return username;
}
String key = Base64.getEncoder().encodeToString(CommonConstant.SIGN_KEY.getBytes());
try {
Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
username = claims.get("user_name").toString();
} catch (Exception ex) {
log.error("用户名解析异常,token:{},key:{}", token, key);
}
return username;
}
/** /**
* 根据请求heard中的token获取用户角色 * 根据请求heard中的token获取用户角色
* *
@ -105,7 +56,6 @@ public class UserUtils {
*/ */
public static void setUser(String username) { public static void setUser(String username) {
THREAD_LOCAL_USER.set(username); THREAD_LOCAL_USER.set(username);
MDC.put(KEY_USER, username); MDC.put(KEY_USER, username);
} }

View File

@ -14,5 +14,5 @@ public class LogVO implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private SysLog sysLog; private SysLog sysLog;
private String token; private String username;
} }

View File

@ -3,19 +3,20 @@ package com.github.pig.gateway.service.impl;
import com.github.pig.common.constant.CommonConstant; import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.constant.MqQueueConstant; import com.github.pig.common.constant.MqQueueConstant;
import com.github.pig.common.entity.SysLog; import com.github.pig.common.entity.SysLog;
import com.github.pig.common.util.UserUtils;
import com.github.pig.common.vo.LogVO; import com.github.pig.common.vo.LogVO;
import com.github.pig.gateway.service.LogSendService; import com.github.pig.gateway.service.LogSendService;
import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.context.RequestContext;
import com.xiaoleilu.hutool.http.HttpUtil; import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.io.IoUtil; import com.xiaoleilu.hutool.io.IoUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.xiaoleilu.hutool.util.URLUtil; import com.xiaoleilu.hutool.util.URLUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -55,7 +56,6 @@ public class LogSendServiceImpl implements LogSendService {
log.setMethod(method); log.setMethod(method);
log.setUserAgent(request.getHeader("user-agent")); log.setUserAgent(request.getHeader("user-agent"));
log.setParams(HttpUtil.toParams(request.getParameterMap())); log.setParams(HttpUtil.toParams(request.getParameterMap()));
log.setCreateBy(UserUtils.getUserName(request));
Long startTime = (Long) requestContext.get("startTime"); Long startTime = (Long) requestContext.get("startTime");
log.setTime(System.currentTimeMillis() - startTime); log.setTime(System.currentTimeMillis() - startTime);
if (requestContext.get(SERVICE_ID) != null) { if (requestContext.get(SERVICE_ID) != null) {
@ -98,10 +98,12 @@ public class LogSendServiceImpl implements LogSendService {
} }
//保存发往MQ只保存授权 //保存发往MQ只保存授权
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && StrUtil.isNotBlank(authentication.getName())) {
LogVO logVo = new LogVO(); LogVO logVo = new LogVO();
log.setCreateBy(authentication.getName());
logVo.setSysLog(log); logVo.setSysLog(log);
if (StringUtils.isNotEmpty(request.getHeader(CommonConstant.REQ_HEADER))) { logVo.setUsername(authentication.getName());
logVo.setToken(request.getHeader(CommonConstant.REQ_HEADER));
rabbitTemplate.convertAndSend(MqQueueConstant.LOG_QUEUE, logVo); rabbitTemplate.convertAndSend(MqQueueConstant.LOG_QUEUE, logVo);
} }
} }

View File

@ -26,9 +26,8 @@ public class LogReceiveListener {
@RabbitHandler @RabbitHandler
public void receive(LogVO logVo) { public void receive(LogVO logVo) {
SysLog sysLog = logVo.getSysLog(); SysLog sysLog = logVo.getSysLog();
String username = UserUtils.getUserName(logVo.getToken()); MDC.put(KEY_USER, logVo.getUsername());
MDC.put(KEY_USER, username); sysLog.setCreateBy(logVo.getUsername());
sysLog.setCreateBy(username);
sysLogService.insert(sysLog); sysLogService.insert(sysLog);
MDC.remove(KEY_USER); MDC.remove(KEY_USER);
} }