将 mall-spring-boot-starter-web 接入新的 system-service 服务

This commit is contained in:
YunaiV
2020-07-04 21:00:34 +08:00
parent c1ca5f7dc5
commit 301e2c5720
49 changed files with 382 additions and 631 deletions

View File

@@ -73,7 +73,7 @@ public class AccountAuthInterceptor extends HandlerInterceptorAdapter {
}
// 设置账号编号
Integer accountId = oauth2AccessTokenResult.getData().getAccountId();
CommonWebUtil.setAccountId(request, accountId);
CommonWebUtil.setUserId(request, accountId);
return accountId;
}

View File

@@ -22,7 +22,7 @@ public class AdminSecurityInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
Integer accountId = CommonWebUtil.getAccountId(request);
Integer accountId = CommonWebUtil.getUserId(request);
if (accountId != null) {
// 获得 Admin 信息
CommonResult<AdminResponse> adminResult = adminRPC.getAdminByAccountId(accountId);

View File

@@ -21,7 +21,7 @@ public class UserSecurityInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
Integer accountId = CommonWebUtil.getAccountId(request);
Integer accountId = CommonWebUtil.getUserId(request);
if (accountId != null) {
// 获得 Admin 信息
CommonResult<UserResponse> userResult = userRPC.getUserByAccountId(accountId);

View File

@@ -15,7 +15,7 @@
<!-- Mall 相关 -->
<dependency>
<groupId>cn.iocoder.mall</groupId>
<artifactId>system-rpc-api</artifactId>
<artifactId>system-service-api</artifactId>
<version>1.0-SNAPSHOT</version>
<optional>true</optional>
</dependency>

View File

@@ -1,10 +1,9 @@
package cn.iocoder.mall.web.config;
import cn.iocoder.mall.web.core.servlet.CorsFilter;
import cn.iocoder.mall.web.core.constant.CommonMallConstants;
import cn.iocoder.mall.web.core.handler.GlobalExceptionHandler;
import cn.iocoder.mall.web.core.handler.GlobalResponseBodyHandler;
import cn.iocoder.mall.web.core.interceptor.AccessLogInterceptor;
import cn.iocoder.mall.web.core.servlet.CorsFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
@@ -40,7 +39,7 @@ public class CommonWebAutoConfiguration implements WebMvcConfigurer {
// ========== 拦截器相关 ==========
@Bean
@ConditionalOnClass(name = {"cn.iocoder.mall.system.rpc.api.systemlog.SystemLogRPC", "org.apache.dubbo.config.annotation.Reference"})
@ConditionalOnClass(name = {"cn.iocoder.mall.systemservice.rpc.systemlog.SystemLogRPC", "org.apache.dubbo.config.annotation.Reference"})
@ConditionalOnMissingBean(AccessLogInterceptor.class)
public AccessLogInterceptor accessLogInterceptor() {
return new AccessLogInterceptor();
@@ -49,8 +48,7 @@ public class CommonWebAutoConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
try {
registry.addInterceptor(this.accessLogInterceptor())
.addPathPatterns(CommonMallConstants.ROOT_PATH_ADMIN + "/**", CommonMallConstants.ROOT_PATH_USER + "/**");
registry.addInterceptor(this.accessLogInterceptor());
logger.info("[addInterceptors][加载 AccessLogInterceptor 拦截器完成]");
} catch (NoSuchBeanDefinitionException e) {
logger.warn("[addInterceptors][无法获取 AccessLogInterceptor 拦截器,因此不启动 AccessLog 的记录]");

View File

@@ -6,19 +6,33 @@ public interface CommonMallConstants {
/**
* 根路径 - 用户
*/
@Deprecated
String ROOT_PATH_USER = "/users";
/**
* 根路径 - 管理员
*/
@Deprecated
String ROOT_PATH_ADMIN = "/admins";
// HTTP Request Attr
/**
* HTTP Request Attr - 账号编号
* HTTP Request Attr - 用户编号
*
* 考虑到 mall-spring-boot-starter-web 不依赖 mall-spring-boot-starter-security但是又希望拿到认证过的用户编号
* 因此通过 Request 的 Attribute 进行共享
*/
String REQUEST_ATTR_USER_ID_KEY = "mall_account_id";
String REQUEST_ATTR_USER_ID_KEY = "mall_user_id";
/**
* HTTP Request Attr - 用户类型
*
* 作用同 {@link #REQUEST_ATTR_USER_ID_KEY}
*/
String REQUEST_ATTR_USER_TYPE_KEY = "mall_user_type";
/**
* HTTP Request Attr - Controller 执行返回
*
* 通过该 Request 的 Attribute获取到请求执行结果从而在访问日志中记录是否成功。
*/
String REQUEST_ATTR_COMMON_RESULT = "mall_common_result";
/**

View File

@@ -6,8 +6,8 @@ import cn.iocoder.common.framework.util.ExceptionUtil;
import cn.iocoder.common.framework.util.HttpUtil;
import cn.iocoder.common.framework.util.MallUtils;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.system.rpc.api.systemlog.SystemLogRPC;
import cn.iocoder.mall.system.rpc.request.systemlog.ExceptionLogAddRequest;
import cn.iocoder.mall.systemservice.rpc.systemlog.SystemLogRPC;
import cn.iocoder.mall.systemservice.rpc.systemlog.dto.ExceptionLogAddDTO;
import cn.iocoder.mall.web.core.util.CommonWebUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.exception.ExceptionUtils;
@@ -33,7 +33,6 @@ public class GlobalExceptionHandler {
// TODO 芋艿,应该还有其它的异常,需要进行翻译
// /**
// * 异常总数 Metrics
// */
@@ -50,20 +49,20 @@ public class GlobalExceptionHandler {
// 逻辑异常
@ExceptionHandler(value = ServiceException.class)
public CommonResult serviceExceptionHandler(HttpServletRequest req, ServiceException ex) {
public CommonResult serviceExceptionHandler(ServiceException ex) {
logger.debug("[serviceExceptionHandler]", ex);
return CommonResult.error(ex.getCode(), ex.getMessage());
}
// Spring MVC 参数不正确
@ExceptionHandler(value = MissingServletRequestParameterException.class)
public CommonResult missingServletRequestParameterExceptionHandler(HttpServletRequest req, MissingServletRequestParameterException ex) {
public CommonResult missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException ex) {
logger.warn("[missingServletRequestParameterExceptionHandler]", ex);
return CommonResult.error(SysErrorCodeEnum.MISSING_REQUEST_PARAM_ERROR.getCode(), SysErrorCodeEnum.MISSING_REQUEST_PARAM_ERROR.getMessage() + ":" + ex.getMessage());
}
@ExceptionHandler(value = ConstraintViolationException.class)
public CommonResult constraintViolationExceptionHandler(HttpServletRequest req, ConstraintViolationException ex) {
public CommonResult constraintViolationExceptionHandler(ConstraintViolationException ex) {
logger.info("[constraintViolationExceptionHandler]", ex);
// TODO 芋艿,后续要想一个更好的方式。
// 拼接详细报错
@@ -77,7 +76,7 @@ public class GlobalExceptionHandler {
public CommonResult exceptionHandler(HttpServletRequest req, Exception e) {
logger.error("[exceptionHandler]", e);
// 插入异常日志
ExceptionLogAddRequest exceptionLog = new ExceptionLogAddRequest();
ExceptionLogAddDTO exceptionLog = new ExceptionLogAddDTO();
try {
// 增加异常计数 metrics TODO 暂时去掉
// EXCEPTION_COUNTER.increment();
@@ -92,9 +91,10 @@ public class GlobalExceptionHandler {
return CommonResult.error(SysErrorCodeEnum.SYS_ERROR.getCode(), SysErrorCodeEnum.SYS_ERROR.getMessage());
}
private void initExceptionLog(ExceptionLogAddRequest exceptionLog, HttpServletRequest request, Exception e) {
private void initExceptionLog(ExceptionLogAddDTO exceptionLog, HttpServletRequest request, Exception e) {
// 设置账号编号
exceptionLog.setAccountId(CommonWebUtil.getAccountId(request));
exceptionLog.setUserId(CommonWebUtil.getUserId(request));
exceptionLog.setUserType(CommonWebUtil.getUserType(request));
// 设置异常字段
exceptionLog.setExceptionName(e.getClass().getName());
exceptionLog.setExceptionMessage(ExceptionUtil.getMessage(e));
@@ -119,13 +119,12 @@ public class GlobalExceptionHandler {
}
@Async
public void addExceptionLog(ExceptionLogAddRequest exceptionLog) {
public void addExceptionLog(ExceptionLogAddDTO exceptionLog) {
try {
systemLogRPC.addExceptionLog(exceptionLog);
} catch (Throwable th) {
logger.error("[addAccessLog][插入异常日志({}) 发生异常({})", JSON.toJSONString(exceptionLog), ExceptionUtils.getRootCauseMessage(th));
}
}
}

View File

@@ -3,8 +3,8 @@ package cn.iocoder.mall.web.core.interceptor;
import cn.iocoder.common.framework.util.HttpUtil;
import cn.iocoder.common.framework.util.MallUtils;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.system.rpc.api.systemlog.SystemLogRPC;
import cn.iocoder.mall.system.rpc.request.systemlog.AccessLogAddRequest;
import cn.iocoder.mall.systemservice.rpc.systemlog.SystemLogRPC;
import cn.iocoder.mall.systemservice.rpc.systemlog.dto.AccessLogAddDTO;
import cn.iocoder.mall.web.core.util.CommonWebUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.exception.ExceptionUtils;
@@ -27,7 +27,7 @@ public class AccessLogInterceptor extends HandlerInterceptorAdapter {
private Logger logger = LoggerFactory.getLogger(getClass());
@Reference(validation = "true", version = "${dubbo.consumer.SystemLogRPC.version}")
@Reference(validation = "false", version = "${dubbo.consumer.SystemLogRPC.version}")
private SystemLogRPC systemLogRPC;
@Value("${spring.application.name}")
@@ -42,7 +42,7 @@ public class AccessLogInterceptor extends HandlerInterceptorAdapter {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
AccessLogAddRequest accessLog = new AccessLogAddRequest();
AccessLogAddDTO accessLog = new AccessLogAddDTO();
try {
// 初始化 accessLog
initAccessLog(accessLog, request);
@@ -54,9 +54,10 @@ public class AccessLogInterceptor extends HandlerInterceptorAdapter {
}
}
private void initAccessLog(AccessLogAddRequest accessLog, HttpServletRequest request) {
private void initAccessLog(AccessLogAddDTO accessLog, HttpServletRequest request) {
// 设置账号编号
accessLog.setAccountId(CommonWebUtil.getAccountId(request));
accessLog.setUserId(CommonWebUtil.getUserId(request));
accessLog.setUserType(CommonWebUtil.getUserType(request));
// 设置访问结果
CommonResult result = CommonWebUtil.getCommonResult(request);
Assert.isTrue(result != null, "result 必须非空");
@@ -75,7 +76,7 @@ public class AccessLogInterceptor extends HandlerInterceptorAdapter {
}
@Async // 异步入库
public void addAccessLog(AccessLogAddRequest accessLog) {
public void addAccessLog(AccessLogAddDTO accessLog) {
try {
systemLogRPC.addAccessLog(accessLog);
} catch (Throwable th) {

View File

@@ -8,14 +8,22 @@ import java.util.Date;
public class CommonWebUtil {
public static Integer getAccountId(ServletRequest request) {
public static Integer getUserId(ServletRequest request) {
return (Integer) request.getAttribute(CommonMallConstants.REQUEST_ATTR_USER_ID_KEY);
}
public static void setAccountId(ServletRequest request, Integer userId) {
public static void setUserId(ServletRequest request, Integer userId) {
request.setAttribute(CommonMallConstants.REQUEST_ATTR_USER_ID_KEY, userId);
}
public static Integer getUserType(ServletRequest request) {
return (Integer) request.getAttribute(CommonMallConstants.REQUEST_ATTR_USER_TYPE_KEY);
}
public static void setUserType(ServletRequest request, Integer userType) {
request.setAttribute(CommonMallConstants.REQUEST_ATTR_USER_TYPE_KEY, userType);
}
public static CommonResult getCommonResult(ServletRequest request) {
return (CommonResult) request.getAttribute(CommonMallConstants.REQUEST_ATTR_COMMON_RESULT);
}