需求
之前ccframe cloud V1用的是springcloud微服务,只需要在header将jwttoken一直传下去就没事,最近弄V2转dubbo发现用户id没有自动保存进数据库表。于是开始研究dubbo如何追踪,顺便把链路追踪ID的问题给一并解决掉。
理论
MDC
MDC(Mapped Diagnostic Context,映射调试上下文)是Slf4j(提供了接口定义和核心实现,日志库负责适配器的实现)提供的一种方便在多线程条件下记录日志的功能。
MDC 可以看成是一个与当前线程绑定的Map,可以往其中添加键值对。MDC 中包含的内容可以被同一线程中执行的代码所访问。当前线程的子线程会继承其父线程中的 MDC 的内容。当需要记录日志时,只需要从 MDC 中获取所需的信息即可。MDC 的内容则由程序在适当的时候保存进去。对于一个 Web 应用来说,通常是在请求被处理的最开始保存这些数据。
简而言之,MDC就是日志框架提供的一个InheritableThreadLocal,项目代码中可以将键值对放入其中,然后使用指定方式取出打印即可。
RpcContext
RpcContext 本质上是一个使用 ThreadLocal 实现的临时状态记录器,RPC请求时会自动给传递给下游服务,当RPC请求结束的时候,当前线程的RpcContex会清空
实现
原理图
生成追踪信息
了解了MDC的原理可知,MDC数据是线程级别的,那么我们可以放在一次线程调用最靠前的位置。对于当前的ccframe系统,我们使用了spring security,而spring security的filter在请求比较靠前的位置,因此我们可以在JwtHeadFilter进行对应的处理。在解析完用户的信息后,将链路ID及会员ID放入MDC。链路ID这里采用Htool的短NanoId形式,因为本身请求会有时间属性,我们只需要在短时间(一次链路请求时间范围),例如几分钟内,不重复即可方便关联日志。这里采用2个记录量:
- userId 记录操作人
- traceId 记录一次链路请求
package org.ccframe.commons.auth;
import cn.hutool.core.lang.id.NanoId;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.JwtException;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.http.HttpStatus;
import org.ccframe.commons.util.IpUtil;
import org.ccframe.commons.util.JwtUtil;
import org.ccframe.commons.util.UUIDUtil;
import org.ccframe.config.GlobalEx;
import org.ccframe.subsys.core.domain.code.RoleCodeEnum;
import org.ccframe.subsys.core.dto.Result;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.slf4j.MDC;
import org.springframework.context.MessageSource;
import org.springframework.http.MediaType;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
public class JwtHeadFilter extends OncePerRequestFilter {
private final RedissonClient redissonClient;
private final LocaleResolver localeResolver;
private final MessageSource messageSource;
public JwtHeadFilter(RedissonClient redissonClient, MessageSource messageSource, LocaleResolver localeResolver) {
this.redissonClient = redissonClient;
this.localeResolver = localeResolver;
this.messageSource = messageSource;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String traceId = NanoId.randomNanoId(8);
MDC.put(GlobalEx.TRACE_ID, traceId);
RpcContext.getContext().setAttachment(GlobalEx.TRACE_ID, traceId); // 同时放入RPC上下文
String uri = request.getRequestURI();
String token = null;
boolean adminUrl = false;
if(uri.startsWith("/" + GlobalEx.ADMIN_URI_PERFIX)) { //后端用户
token = request.getHeader(GlobalEx.ADMIN_TOKEN);
adminUrl = true;
}else if(uri.startsWith("/" + GlobalEx.API_URI_PERFIX)) { //前端用户
token = request.getHeader(GlobalEx.API_TOKEN);
}else {
filterChain.doFilter(request, response);
return;
}
if (!adminUrl && StringUtils.isEmpty(token)){ // 前台的直接退出了
filterChain.doFilter(request,response);
return;
}
List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
TokenUser tokenUser = null;
if(StringUtils.isNotEmpty(token)){ //有token情况
try {
tokenUser = JwtUtil.decodeData(token, TokenUser.class);
authorityList = tokenUser.getRoleIds().stream().map(item->new SimpleGrantedAuthority("ROLE_"+item)).collect(Collectors.toList());
}catch(IllegalArgumentException|JwtException e) { //构造无权访问的json返回信息
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache, must-revalidate");
try {
Locale currentLocale = localeResolver.resolveLocale(request);
String message = messageSource.getMessage("errors.auth.noAuth", GlobalEx.EMPTY_ARGS, currentLocale); // 未登陆/无权限
response.getWriter().write(JSON.toJSONString(Result.error(HttpStatus.SC_FORBIDDEN, message, "errors.auth.noAuth", e.getMessage())));
logger.error(e.getMessage());
response.flushBuffer();
return;
} catch (IOException ioe) {
logger.error("与客户端通讯异常:" + e.getMessage(), e);
e.printStackTrace();
}
}
}
if(adminUrl) { // 后台,尝试匹配IP白名单
String remoteIp = IpUtil.getRemoteIp(request);
RBucket<String> whiteIpBucket = redissonClient.getBucket(GlobalEx.CACHKEY_WHITE_IP, StringCodec.INSTANCE);
String whiteIp = whiteIpBucket.get();
if(StringUtils.isNotEmpty(remoteIp) && StringUtils.isNotEmpty(whiteIp) && remoteIp.equals(whiteIp)){ // 后台操作匹配白名单权限
authorityList.add(new SimpleGrantedAuthority("ROLE_" + RoleCodeEnum.WHITE_IP.toCode()));
}
}
if(!authorityList.isEmpty()){
//认证,根据ROLE集合解析即可
JwtAuthenticationToken jwtAuthenticationToken = new JwtAuthenticationToken(
tokenUser, // 如果只是IP白名单直接访问,tokenUser可能为Null
authorityList
);
MDC.put(GlobalEx.TRACE_USER_ID, tokenUser.getUserId().toString());
RpcContext.getContext().setAttachment(GlobalEx.TRACE_USER_ID, tokenUser.getUserId().toString()); // 同时放入RPC上下文
jwtAuthenticationToken.setDetails(new WebAuthenticationDetails(request));
SecurityContextHolder.getContext().setAuthentication(jwtAuthenticationToken); //授权对象放入上下文
}
filterChain.doFilter(request,response);
}
}
传递信息
生成MDC信息后,我们需要在dubbo服务请求时进行传递。dubbo的RpcContext机制能够保证数据传递到下游的处理服务。唯一要做的是把RpcContext放入到MDC,这样下游服务里的所有日志都具备链路信息了。dubbo有一个扩展机制,可以在消费服务的时候进行切面处理。定义对应的Bean即可
package org.ccframe.commons.helper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.ccframe.config.GlobalEx;
import org.slf4j.MDC;
@Activate(group = {"provider"})
public class TraceProviderFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
String traceId = RpcContext.getContext().getAttachment(GlobalEx.TRACE_ID);
if (traceId != null) {
MDC.put(GlobalEx.TRACE_ID, traceId);
};
String traceUserId = RpcContext.getContext().getAttachment(GlobalEx.TRACE_USER_ID);
if (traceId != null) {
MDC.put(GlobalEx.TRACE_USER_ID, traceId);
};
try {
return invoker.invoke(invocation);
} finally {
MDC.remove(GlobalEx.TRACE_ID);
MDC.remove(GlobalEx.TRACE_USER_ID);
}
}
}
关联操作数据
这个是原来就实现的自动记录操作人的方案。原理是采用JPA的EntityListeners方案持久化监听器,原方案是在springsecurity的上下文里获取,由于微服务后请求跨机器,因此改从MDC里获取(前面已经把RpcContext放入到MDC了)
这个是数据库操作基类,EntityListeners注解定义
package org.ccframe.commons.base;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.ccframe.commons.helper.EntityOperationListener;
import org.ccframe.config.GlobalEx;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import javax.persistence.*;
import java.util.Date;
/**
* SAAS数据操作基础类
* @author JIM
*
*/
@MappedSuperclass
@Setter
@Getter
@EntityListeners({EntityOperationListener.class})
public abstract class BaseEntity implements IBaseEntity {
private static final long serialVersionUID = -5656014821398158846L;
public static final String CREATE_TIME = "createTime";
public static final String UPDATE_TIME = "updateTime";
public static final String CREATE_USER_ID = "createUserId"; //创建人
public static final String UPDATE_USER_ID = "updateUserId"; //最后修改人
public static final String TENANT_ID = "tenantId"; // 租户,所有资源按照租户隔离,提供检测annotation
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATE_TIME", nullable = false, length = 0, updatable = false)
//elasticsearch
@Field(type = FieldType.Date, format = DateFormat.custom, pattern = GlobalEx.ES_DATE_PATTERN)
@JsonFormat (shape = JsonFormat.Shape.STRING, pattern = GlobalEx.STANDERD_DATE_FORMAT, timezone = GlobalEx.TIMEZONE)
private Date createTime;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "UPDATE_TIME", nullable = false, length = 0)
//elasticsearch
@Field(type = FieldType.Date, format = DateFormat.custom, pattern = GlobalEx.ES_DATE_PATTERN)
@JsonFormat (shape = JsonFormat.Shape.STRING, pattern = GlobalEx.STANDERD_DATE_FORMAT, timezone = GlobalEx.TIMEZONE)
private Date updateTime;
@Column(name = "CREATE_USER_ID", nullable = true, length = 10, updatable = false)
@Field(type = FieldType.Integer)
private Integer createUserId;
@Column(name = "UPDATE_USER_ID", nullable = true, length = 10)
@Field(type = FieldType.Integer)
private Integer updateUserId;
@Column(name = "TENANT_ID", nullable = true, length = 10)
@Field(type = FieldType.Integer)
private Integer tenantId;
@Override
public boolean equals(Object obj) {
if(!(getClass().isInstance(obj))){
return false;
}
if(this == obj){
return true;
}
BaseEntity other = (BaseEntity)obj;
return new EqualsBuilder()
.append(getId(),other.getId())
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(getId())
.toHashCode();
}
}
然后EntityListeners里实现持久化新增和更新逻辑
package org.ccframe.commons.helper;
import org.ccframe.commons.auth.TokenUser;
import org.ccframe.commons.base.BaseEntity;
import org.ccframe.commons.base.IBaseEntity;
import org.ccframe.config.GlobalEx;
import org.slf4j.MDC;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
import java.util.Date;
public class EntityOperationListener {
private ICcTransactionHelper ccTransactionHelper;
private ICcTransactionHelper getCcTransactionHelper(){
if(ccTransactionHelper == null){
ccTransactionHelper = SpringContextHelper.getBean(ICcTransactionHelper.class);
}
return ccTransactionHelper;
}
@PrePersist
protected void onCreate(Object baseEntity) {
IBaseEntity targetEntity = (IBaseEntity)baseEntity;
//采用dubbo的MDC透传操作用户userId及请求ID
String userId = MDC.get(GlobalEx.TRACE_USER_ID);
if(userId != null) { // MDC上下文里有
targetEntity.setCreateUserId(Integer.valueOf(userId));
}
Date now = new Date();
targetEntity.setCreateTime(now);
targetEntity.setUpdateTime(now);
getCcTransactionHelper().pushSave(targetEntity);
}
@PreUpdate
protected void onUpdate(Object baseEntity) {
IBaseEntity targetEntity = (IBaseEntity)baseEntity;
//采用dubbo的MDC透传操作用户userId及请求ID
String userId = MDC.get(GlobalEx.TRACE_USER_ID);
if(userId != null) { // MDC上下文里有
targetEntity.setUpdateUserId(Integer.valueOf(userId));
}
targetEntity.setUpdateTime(new Date());
getCcTransactionHelper().pushSave(targetEntity);
}
@PreRemove
protected void onRemove(BaseEntity baseEntity) {
getCcTransactionHelper().pushDelete(baseEntity);
}
}
新增和修改操作一下,看到对应的新增用户和修改用户记录都写入了。这样每个表都具备了简单操作记录