Seata事务ID的传递
https://www.cnblogs.com/ciel717/p/16185061.html
发送:SeataFeignClient
替换了默认的feignClient
,把xid
放到了requestHeader
里。
SeataFeignClient.execute:塞到消息头
@Override public Response execute(Request request, Request.Options options) throws IOException { //设置xid Request modifiedRequest = getModifyRequest(request); //调用下游服务 return this.delegate.execute(modifiedRequest, options); } private Request getModifyRequest(Request request) { String xid = RootContext.getXID(); if (StringUtils.isEmpty(xid)) { return request; } Map<String, Collection<String>> headers = new HashMap<>(MAP_SIZE); //设置xid到消息头 headers.putAll(request.headers()); List<String> seataXid = new ArrayList<>(); seataXid.add(xid); headers.put(RootContext.KEY_XID, seataXid); return Request.create(request.method(), request.url(), headers, request.body(),request.charset()); }
- 接收:拦截器实现
SeataHandlerInterceptor.preHandle():通过WebMvcConfigure::addInterceptors中绑定该拦截器
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) { String xid = RootContext.getXID(); //从消息头中获取xid String rpcXid = request.getHeader(RootContext.KEY_XID); if (log.isDebugEnabled()) { log.debug("xid in RootContext {} xid in RpcContext {}", xid, rpcXid); } if (xid == null && rpcXid != null) { // 设置xid RootContext.bind(rpcXid); if (log.isDebugEnabled()) { log.debug("bind {} to RootContext", rpcXid); } } return true; }
@OverridepublicResponseexecute(Request request, Request.Options options) throws IOException { //设置xidRequest modifiedRequest = getModifyRequest(request); //调用下游服务returnthis.delegate.execute(modifiedRequest, options); } privateRequestgetModifyRequest(Request request) { String xid = RootContext.getXID(); if (StringUtils.isEmpty(xid)) { return request; } Map<String, Collection<String>> headers = newHashMap<>(MAP_SIZE); //设置xid到消息头 headers.putAll(request.headers()); List<String> seataXid = newArrayList<>(); seataXid.add(xid); headers.put(RootContext.KEY_XID, seataXid); returnRequest.create(request.method(), request.url(), headers, request.body(),request.charset()); } 标签:RootContext,xid,Seata,request,Request,seataXid,headers From: https://www.cnblogs.com/clarino/p/16972033.html