com.alipay.sofa.rpc.context.RpcInternalContext Java Examples
The following examples show how to use
com.alipay.sofa.rpc.context.RpcInternalContext.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SyncInvokeClientHandler.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public void doOnException(Throwable e) { if (rpcFuture == null) { return; } ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.classLoader); RpcInternalContext.setContext(context); rpcFuture.setFailure(e); } finally { Thread.currentThread().setContextClassLoader(cl); RpcInvokeContext.removeContext(); RpcInternalContext.removeAllContext(); } }
Example #2
Source File: ConsumerTracerFilter.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException { SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); SofaTracerSpan clientSpan = sofaTraceContext.getCurrentSpan(); clientSpan.setTag(RpcSpanTags.INVOKE_TYPE, request.getInvokeType()); RpcInternalContext context = RpcInternalContext.getContext(); clientSpan.setTag(RpcSpanTags.ROUTE_RECORD, (String) context.getAttachment(RpcConstants.INTERNAL_KEY_ROUTER_RECORD)); ProviderInfo providerInfo = context.getProviderInfo(); if (providerInfo != null) { clientSpan.setTag(RpcSpanTags.REMOTE_APP, providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_APP_NAME)); clientSpan.setTag(RpcSpanTags.REMOTE_IP, providerInfo.getHost() + ":" + providerInfo.getPort()); } return invoker.invoke(request); // 因为异步的场景,所以received不写在这里 }
Example #3
Source File: RpcSofaTracer.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public void checkState() { RpcInternalContext rpcInternalContext = RpcInternalContext.getContext(); //tracer 上下文 SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); if (rpcInternalContext.isConsumerSide()) { //客户端 tracer 堆栈中最多有 1 个(客户端 span 完毕,服务端 span 压栈所以最多一个) if (sofaTraceContext.getThreadLocalSpanSize() > 1) { SelfLog.error(LogCodes.getLog(LogCodes.ERROR_TRACER_CONSUMER_STACK)); SelfLog.flush(); } } else if (rpcInternalContext.isProviderSide()) { //服务端 tracer 堆栈中应该为 0 个 if (sofaTraceContext.getThreadLocalSpanSize() > 0) { SelfLog.error(LogCodes.getLog(LogCodes.ERROR_TRACER_PROVIDER_STACK)); SelfLog.flush(); } } }
Example #4
Source File: RestTracerAdapter.java From sofa-rpc with Apache License 2.0 | 6 votes |
/** * 存入tracer信息 * * @param requestContext ClientRequestContext */ public static void beforeSend(ClientRequestContext requestContext) { // tracer信息放入request 发到服务端 SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext(); SofaTracerSpan clientSpan = sofaTraceContext.getCurrentSpan(); RpcInternalContext context = RpcInternalContext.getContext(); if (clientSpan != null) { requestContext.getHeaders().add(RemotingConstants.NEW_RPC_TRACE_NAME, clientSpan.getSofaTracerSpanContext().serializeSpanContext()); } // 客户端发送自己的应用名 String appName = (String) context.getAttachment(INTERNAL_KEY_APP_NAME); if (appName != null) { requestContext.getHeaders().add(RemotingConstants.HEAD_APP_NAME, appName); } RestBaggageItemsHandler.encodeBaggageItemToRequest(requestContext.getHeaders()); }
Example #5
Source File: SofaAsyncHystrixCommand.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override protected Object run() throws Exception { events.add(SofaAsyncHystrixEvent.EMIT); RpcInternalContext.setContext(rpcInternalContext); RpcInvokeContext.setContext(rpcInvokeContext); this.sofaResponse = invoker.invoke(request); ResponseFuture responseFuture = RpcInternalContext.getContext().getFuture(); lock.countDown(); events.add(SofaAsyncHystrixEvent.INVOKE_UNLOCKED); try { return responseFuture.get(); } finally { events.add(SofaAsyncHystrixEvent.INVOKE_SUCCESS); } }
Example #6
Source File: TraceClientRequestFilter.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public void filter(ClientRequestContext requestContext) throws IOException { try { if (RpcInternalContext.isAttachmentEnable()) { // 补充客户端request长度 RpcInternalContext context = RpcInternalContext.getContext(); context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE, requestContext.getHeaderString(HttpHeaders.CONTENT_LENGTH)); } RestTracerAdapter.beforeSend(requestContext); } catch (Exception e) { logger.error(LogCodes.getLog(LogCodes.ERROR_TRACER_UNKNOWN_EXP, "filter", "rest", "client"), e); } }
Example #7
Source File: SofaAsyncHystrixCommand.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public SofaResponse invoke() { if (isCircuitBreakerOpen() && LOGGER.isWarnEnabled(invoker.getConfig().getAppName())) { LOGGER.warnWithApp(invoker.getConfig().getAppName(), "Circuit Breaker is opened, method: {}#{}", invoker.getConfig().getInterfaceId(), request.getMethodName()); } HystrixResponseFuture delegate = new HystrixResponseFuture(this.queue()); try { boolean finished = lock.await(getLockTimeout(), TimeUnit.MILLISECONDS); if (!finished && !this.isExecutionComplete()) { throw new SofaTimeOutException( "Asynchronous execution timed out, please check Hystrix configuration. Events: " + getExecutionEventsString()); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } RpcInternalContext.getContext().setFuture(delegate); if (this.sofaResponse == null) { this.sofaResponse = buildEmptyResponse(request); } return this.sofaResponse; }
Example #8
Source File: SofaRpcMetrics.java From sofa-rpc with Apache License 2.0 | 6 votes |
private void onEvent(ClientEndInvokeEvent event) { InvokeMeta meta = new InvokeMeta( event.getRequest(), event.getResponse(), getLongAvoidNull(RpcInternalContext.getContext().getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE)) ); RpcInternalContext context = RpcInternalContext.getContext(); Duration elapsed = meta.elapsed(); Tags tags = meta.tags(this.common); clientTotal.apply(tags).record(elapsed); if (!meta.success()) { clientFail.apply(tags).record(elapsed); } requestSize.apply(tags).record(getLongAvoidNull( context.getAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE))); responseSize.apply(tags).record(getLongAvoidNull( context.getAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE))); }
Example #9
Source File: RestLookoutAdapter.java From sofa-rpc with Apache License 2.0 | 6 votes |
public static void sendRestServerSendEvent(RestServerSendEvent restServerSendEvent) { //this is special for rest if (EventBus.isEnable(ServerSendEvent.class)) { SofaRequest request = new SofaRequest(); String appName = (String) RpcRuntimeContext.get(RpcRuntimeContext.KEY_APPNAME); request.setTargetAppName(appName); request.addRequestProp(RemotingConstants.HEAD_APP_NAME, restServerSendEvent.getRequest().getHttpHeaders() .getHeaderString(RemotingConstants.HEAD_APP_NAME)); RpcInternalContext context = RpcInternalContext.getContext(); request.setTargetServiceUniqueName((String) context.getAttachment(INTERNAL_KEY_PREFIX + RestConstants.REST_SERVICE_KEY)); request.setMethodName((String) context.getAttachment(INTERNAL_KEY_PREFIX + RestConstants.REST_METHODNAME_KEY)); request.addRequestProp(RemotingConstants.HEAD_PROTOCOL, RpcConstants.PROTOCOL_TYPE_REST); request.setInvokeType(RpcConstants.INVOKER_TYPE_SYNC); SofaResponse response = new SofaResponse(); if (restServerSendEvent.getThrowable() != null) { response.setErrorMsg(restServerSendEvent.getThrowable().getMessage()); } final ServerSendEvent event = new ServerSendEvent(request, response, restServerSendEvent.getThrowable()); EventBus.post(event); } }
Example #10
Source File: AbstractInvokeCallbackTest.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Test public void testRecordClientElapseTime() { BoltInvokerCallback invokerCallback = new BoltInvokerCallback(null, null, null, null, null, null); invokerCallback.recordClientElapseTime(); Long elapse = (Long) RpcInternalContext.getContext().getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE); Assert.assertNull(elapse); RpcInternalContext context = RpcInternalContext.getContext(); invokerCallback = new BoltInvokerCallback(null, null, null, null, context, null); invokerCallback.recordClientElapseTime(); elapse = (Long) context.getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE); Assert.assertNull(elapse); context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME, RpcRuntimeContext.now() - 1000); invokerCallback.recordClientElapseTime(); elapse = (Long) context.getAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE); Assert.assertNotNull(elapse); }
Example #11
Source File: SofaRpcSerialization.java From sofa-rpc with Apache License 2.0 | 6 votes |
/** * 客户端记录响应反序列化大小和响应反序列化耗时 * * @param responseCommand 响应体 */ private void recordDeserializeResponse(RpcResponseCommand responseCommand, InvokeContext invokeContext) { if (!RpcInternalContext.isAttachmentEnable()) { return; } RpcInternalContext context = null; if (invokeContext != null) { // 客户端异步调用的情况下,上下文会放在InvokeContext中传递 context = invokeContext.get(RemotingConstants.INVOKE_CTX_RPC_CTX); } if (context == null) { context = RpcInternalContext.getContext(); } int cost = context.getStopWatch().tick().read(); int respSize = RpcProtocol.getResponseHeaderLength() + responseCommand.getClazzLength() + responseCommand.getContentLength() + responseCommand.getHeaderLength(); // 记录响应反序列化大小和响应反序列化耗时 context.setAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE, respSize); context.setAttachment(RpcConstants.INTERNAL_KEY_RESP_DESERIALIZE_TIME, cost); }
Example #12
Source File: SofaRpcSerialization.java From sofa-rpc with Apache License 2.0 | 6 votes |
/** * 客户端记录序列化请求的耗时和 * * @param requestCommand 请求对象 */ protected void recordSerializeRequest(RequestCommand requestCommand, InvokeContext invokeContext) { if (!RpcInternalContext.isAttachmentEnable()) { return; } RpcInternalContext context = null; if (invokeContext != null) { // 客户端异步调用的情况下,上下文会放在InvokeContext中传递 context = invokeContext.get(RemotingConstants.INVOKE_CTX_RPC_CTX); } if (context == null) { context = RpcInternalContext.getContext(); } int cost = context.getStopWatch().tick().read(); int requestSize = RpcProtocol.getRequestHeaderLength() + requestCommand.getClazzLength() + requestCommand.getContentLength() + requestCommand.getHeaderLength(); // 记录请求序列化大小和请求序列化耗时 context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE, requestSize); context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SERIALIZE_TIME, cost); }
Example #13
Source File: SofaRpcSerialization.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public <Request extends RequestCommand> boolean deserializeHeader(Request request) throws DeserializationException { if (request instanceof RpcRequestCommand) { RpcInternalContext.getContext().getStopWatch().tick(); RpcRequestCommand requestCommand = (RpcRequestCommand) request; if (requestCommand.getRequestHeader() != null) { // 代表已经提前解析过了,例如使用自定义业务线程池的时候,bolt会提前解析变长Header的数据 return true; } byte[] header = requestCommand.getHeader(); // 解析头部 Map<String, String> headerMap = mapSerializer.decode(header); requestCommand.setRequestHeader(headerMap); RpcInvokeContext.getContext().put(RpcConstants.SOFA_REQUEST_HEADER_KEY, Collections.unmodifiableMap(headerMap)); return true; } return false; }
Example #14
Source File: SofaRpcSerialization.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public <Request extends RequestCommand> boolean serializeHeader(Request request, InvokeContext invokeContext) throws SerializationException { if (request instanceof RpcRequestCommand) { RpcInternalContext.getContext().getStopWatch().tick(); RpcRequestCommand requestCommand = (RpcRequestCommand) request; Object requestObject = requestCommand.getRequestObject(); String service = getTargetServiceName(requestObject); if (StringUtils.isNotEmpty(service)) { Map<String, String> header = new HashMap<String, String>(16); header.put(RemotingConstants.HEAD_SERVICE, service); putRequestMetadataToHeader(requestObject, header); requestCommand.setHeader(mapSerializer.encode(header)); } return true; } return false; }
Example #15
Source File: SofaRpcSerialization.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public <Response extends ResponseCommand> boolean serializeHeader(Response response) throws SerializationException { if (response instanceof RpcResponseCommand) { RpcInternalContext.getContext().getStopWatch().tick(); Object responseObject = ((RpcResponseCommand) response).getResponseObject(); if (responseObject instanceof SofaResponse) { SofaResponse sofaResponse = (SofaResponse) responseObject; if (sofaResponse.isError() || sofaResponse.getAppResponse() instanceof Throwable) { sofaResponse.addResponseProp(RemotingConstants.HEAD_RESPONSE_ERROR, StringUtils.TRUE); } response.setHeader(mapSerializer.encode(sofaResponse.getResponseProps())); } return true; } return false; }
Example #16
Source File: BoltClientTransport.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public void oneWaySend(SofaRequest request, int timeout) throws SofaRpcException { checkConnection(); RpcInternalContext context = RpcInternalContext.getContext(); InvokeContext invokeContext = createInvokeContext(request); SofaRpcException throwable = null; try { beforeSend(context, request); doOneWay(request, invokeContext, timeout); } catch (Exception e) { // 其它异常 throwable = convertToRpcException(e); throw throwable; } finally { afterSend(context, invokeContext, request); if (EventBus.isEnable(ClientSyncReceiveEvent.class)) { EventBus.post(new ClientSyncReceiveEvent(transportConfig.getConsumerConfig(), transportConfig.getProviderInfo(), request, null, throwable)); } } }
Example #17
Source File: BoltClientTransport.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public SofaResponse syncSend(SofaRequest request, int timeout) throws SofaRpcException { checkConnection(); RpcInternalContext context = RpcInternalContext.getContext(); InvokeContext boltInvokeContext = createInvokeContext(request); SofaResponse response = null; SofaRpcException throwable = null; try { beforeSend(context, request); response = doInvokeSync(request, boltInvokeContext, timeout); return response; } catch (Exception e) { // 其它异常 throwable = convertToRpcException(e); throw throwable; } finally { afterSend(context, boltInvokeContext, request); if (EventBus.isEnable(ClientSyncReceiveEvent.class)) { EventBus.post(new ClientSyncReceiveEvent(transportConfig.getConsumerConfig(), transportConfig.getProviderInfo(), request, response, throwable)); } } }
Example #18
Source File: SyncInvokeClientHandler.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public void doOnResponse(Object result) { if (rpcFuture == null) { return; } ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); SofaResponse response = (SofaResponse) result; try { Thread.currentThread().setContextClassLoader(this.classLoader); RpcInternalContext.setContext(context); decode(response); rpcFuture.setSuccess(response); } finally { Thread.currentThread().setContextClassLoader(oldCl); RpcInvokeContext.removeContext(); RpcInternalContext.removeAllContext(); } }
Example #19
Source File: AbstractCustomHessianSerializer.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * @param serialize true is serialize, false is deserialize. */ private int getErrorCode(boolean serialize) { if (RpcInternalContext.getContext().isProviderSide()) { return serialize ? RpcErrorType.SERVER_SERIALIZE : RpcErrorType.SERVER_DESERIALIZE; } else if (RpcInternalContext.getContext().isConsumerSide()) { return serialize ? RpcErrorType.CLIENT_SERIALIZE : RpcErrorType.CLIENT_DESERIALIZE; } else { return RpcErrorType.UNKNOWN; } }
Example #20
Source File: BoltClientTransport.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * 调用后设置一些属性(注意,在异步的情况较多下) * * @param context RPC上下文 * @param invokeContext bolt调用上下文 * @param request 请求对象 */ protected void afterSend(RpcInternalContext context, InvokeContext invokeContext, SofaRequest request) { currentRequests.decrementAndGet(); if (RpcInternalContext.isAttachmentEnable()) { putToContextIfNotNull(invokeContext, InvokeContext.CLIENT_CONN_CREATETIME, context, RpcConstants.INTERNAL_KEY_CONN_CREATE_TIME); } if (EventBus.isEnable(ClientAfterSendEvent.class)) { EventBus.post(new ClientAfterSendEvent(request)); } }
Example #21
Source File: BoltClientTransport.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * 调用前设置一些属性 * * @param context RPC上下文 * @param request 请求对象 */ protected void beforeSend(RpcInternalContext context, SofaRequest request) { currentRequests.incrementAndGet(); context.setLocalAddress(localAddress()); if (EventBus.isEnable(ClientBeforeSendEvent.class)) { EventBus.post(new ClientBeforeSendEvent(request)); } }
Example #22
Source File: SofaRpcSerialization.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * 服务端记录序列化响应的大小和耗时 * * @param responseCommand 响应体 */ private void recordSerializeResponse(RpcResponseCommand responseCommand) { if (!RpcInternalContext.isAttachmentEnable()) { return; } RpcInternalContext context = RpcInternalContext.getContext(); int cost = context.getStopWatch().tick().read(); int respSize = RpcProtocol.getResponseHeaderLength() + responseCommand.getClazzLength() + responseCommand.getContentLength() + responseCommand.getHeaderLength(); // 记录响应序列化大小和请求序列化耗时 context.setAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE, respSize); context.setAttachment(RpcConstants.INTERNAL_KEY_RESP_SERIALIZE_TIME, cost); }
Example #23
Source File: SofaHystrixCommand.java From sofa-rpc with Apache License 2.0 | 5 votes |
public SofaHystrixCommand(FilterInvoker invoker, SofaRequest request) { super(SofaHystrixConfig.loadSetterFactory((ConsumerConfig) invoker.getConfig()).createSetter(invoker, request)); this.rpcInternalContext = RpcInternalContext.peekContext(); this.rpcInvokeContext = RpcInvokeContext.peekContext(); this.invoker = invoker; this.request = request; }
Example #24
Source File: DubooServerTest.java From sofa-rpc with Apache License 2.0 | 5 votes |
@After public void afterMethod() { DubboSingleton.destroyAll(); RpcRuntimeContext.destroy(); RpcInternalContext.removeAllContext(); RpcInvokeContext.removeContext(); }
Example #25
Source File: SofaAsyncHystrixCommand.java From sofa-rpc with Apache License 2.0 | 5 votes |
public SofaAsyncHystrixCommand(FilterInvoker invoker, SofaRequest request) { super(SofaHystrixConfig.loadSetterFactory((ConsumerConfig) invoker.getConfig()).createSetter(invoker, request)); this.rpcInternalContext = RpcInternalContext.peekContext(); this.rpcInvokeContext = RpcInvokeContext.peekContext(); this.invoker = invoker; this.request = request; }
Example #26
Source File: BoltFutureInvokeCallback.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Override public void onException(Throwable e) { if (rpcFuture == null) { return; } ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.classLoader); RpcInternalContext.setContext(context); if (EventBus.isEnable(ClientAsyncReceiveEvent.class)) { EventBus.post(new ClientAsyncReceiveEvent(consumerConfig, providerInfo, request, null, e)); } // do async filter after respond server FilterChain chain = consumerConfig.getConsumerBootstrap().getCluster().getFilterChain(); if (chain != null) { chain.onAsyncResponse(consumerConfig, request, null, e); } recordClientElapseTime(); if (EventBus.isEnable(ClientEndInvokeEvent.class)) { EventBus.post(new ClientEndInvokeEvent(request, null, e)); } rpcFuture.setFailure(e); } finally { Thread.currentThread().setContextClassLoader(cl); RpcInvokeContext.removeContext(); RpcInternalContext.removeAllContext(); } }
Example #27
Source File: BoltClientTransport.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Override public ResponseFuture asyncSend(SofaRequest request, int timeout) throws SofaRpcException { checkConnection(); RpcInternalContext context = RpcInternalContext.getContext(); InvokeContext boltInvokeContext = createInvokeContext(request); try { beforeSend(context, request); boltInvokeContext.put(RemotingConstants.INVOKE_CTX_RPC_CTX, context); return doInvokeAsync(request, context, boltInvokeContext, timeout); } catch (Exception e) { throw convertToRpcException(e); } finally { afterSend(context, boltInvokeContext, request); } }
Example #28
Source File: AbstractInvokeCallback.java From sofa-rpc with Apache License 2.0 | 5 votes |
protected AbstractInvokeCallback(ConsumerConfig consumerConfig, ProviderInfo providerInfo, SofaRequest request, RpcInternalContext context, ClassLoader classLoader) { this.consumerConfig = consumerConfig; this.providerInfo = providerInfo; this.request = request; this.context = context; this.classLoader = classLoader; }
Example #29
Source File: BaseZkTest.java From sofa-rpc with Apache License 2.0 | 5 votes |
@AfterClass public static void adAfterClass() { RpcRuntimeContext.destroy(); RpcInternalContext.removeContext(); RpcInvokeContext.removeContext(); if (server != null) { try { server.stop(); } catch (IOException e) { e.printStackTrace(); } } }
Example #30
Source File: ConsumerInvoker.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Override public SofaResponse invoke(SofaRequest sofaRequest) throws SofaRpcException { // 设置下服务器应用 ProviderInfo providerInfo = RpcInternalContext.getContext().getProviderInfo(); String appName = providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_APP_NAME); if (StringUtils.isNotEmpty(appName)) { sofaRequest.setTargetAppName(appName); } // 目前只是通过client发送给服务端 return consumerBootstrap.getCluster().sendMsg(providerInfo, sofaRequest); }