com.alipay.sofa.rpc.core.request.SofaRequest Java Examples
The following examples show how to use
com.alipay.sofa.rpc.core.request.SofaRequest.
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: 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 #2
Source File: GenericServiceImpl.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public void generic(Request request, StreamObserver<Response> responseObserver) { SofaRequest sofaRequest = TracingContextKey.getKeySofaRequest().get(Context.current()); String methodName = sofaRequest.getMethodName(); Class[] argTypes = getArgTypes(request); try { Serializer serializer = SerializerFactory.getSerializer(request.getSerializeType()); Method declaredMethod = proxyClass.getDeclaredMethod(methodName, argTypes); Object result = declaredMethod.invoke(ref, getInvokeArgs(request, argTypes, serializer)); Response.Builder builder = Response.newBuilder(); builder.setSerializeType(request.getSerializeType()); builder.setType(declaredMethod.getReturnType().getName()); builder.setData(ByteString.copyFrom(serializer.encode(result, null).array())); Response build = builder.build(); responseObserver.onNext(build); responseObserver.onCompleted(); } catch (Exception e) { LOGGER.error("Invoke " + methodName + " error:", e); throw new SofaRpcRuntimeException(e); } }
Example #3
Source File: AbstractCluster.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public SofaResponse invoke(SofaRequest request) throws SofaRpcException { SofaResponse response = null; try { //为什么要放在这里,因为走了filter的话,就要求有地址了 if (consumerConfig.isMock()) { return doMockInvoke(request); } // 做一些初始化检查,例如未连接可以连接 checkClusterState(); // 开始调用 countOfInvoke.incrementAndGet(); // 计数+1 response = doInvoke(request); return response; } catch (SofaRpcException e) { // 客户端收到异常(客户端自己的异常) throw e; } finally { countOfInvoke.decrementAndGet(); // 计数-1 } }
Example #4
Source File: SofaRpcUtils.java From Sentinel with Apache License 2.0 | 6 votes |
public static String getMethodResourceName(SofaRequest request) { StringBuilder buf = new StringBuilder(64); buf.append(request.getInterfaceName()) .append("#") .append(request.getMethodName()) .append("("); boolean isFirst = true; for (String methodArgSig : request.getMethodArgSigs()) { if (!isFirst) { buf.append(","); } else { isFirst = false; } buf.append(methodArgSig); } buf.append(")"); return buf.toString(); }
Example #5
Source File: FailFastCluster.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public SofaResponse doInvoke(SofaRequest request) throws SofaRpcException { ProviderInfo providerInfo = select(request); try { SofaResponse response = filterChain(providerInfo, request); if (response != null) { return response; } else { throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, "Failed to call " + request.getInterfaceName() + "." + request.getMethodName() + " on remote server " + providerInfo + ", return null"); } } catch (Exception e) { throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, "Failed to call " + request.getInterfaceName() + "." + request.getMethodName() + " on remote server: " + providerInfo + ", cause by: " + e.getClass().getName() + ", message is: " + e.getMessage(), e); } }
Example #6
Source File: SofaRpcProviderInterceptor.java From skywalking with Apache License 2.0 | 6 votes |
@Override public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable { SofaRequest sofaRequest = (SofaRequest) allArguments[0]; AbstractSpan span = null; ContextCarrier contextCarrier = new ContextCarrier(); CarrierItem next = contextCarrier.items(); while (next.hasNext()) { next = next.next(); final String headKey = next.getHeadKey(); final Object attachment = sofaRequest.getRequestProp(SKYWALKING_PREFIX + headKey); if (attachment != null) { next.setHeadValue(attachment.toString()); } else { next.setHeadValue(""); } } span = ContextManager.createEntrySpan(generateViewPoint(sofaRequest), contextCarrier); span.setComponent(ComponentsDefine.SOFARPC); SpanLayer.asRPCFramework(span); }
Example #7
Source File: CustomEchoFilter.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException { LOGGER.info("echo request : {}, {}", request.getInterfaceName() + "." + request.getMethodName(), request.getMethodArgs()); SofaResponse response = invoker.invoke(request); if (response == null) { return response; } else if (response.isError()) { LOGGER.info("server rpc error: {}", response.getErrorMsg()); } else { Object ret = response.getAppResponse(); if (ret instanceof Throwable) { LOGGER.error("server biz error: {}", (Throwable) ret); } else { LOGGER.info("echo response : {}", response.getAppResponse()); } } return response; }
Example #8
Source File: AbstractHttp2ClientTransport.java From sofa-rpc with Apache License 2.0 | 6 votes |
protected FullHttpRequest convertToHttpRequest(SofaRequest request) { HttpScheme scheme = SslContextBuilder.SSL ? HttpScheme.HTTPS : HttpScheme.HTTP; AsciiString hostName = new AsciiString(providerInfo.getHost() + ':' + providerInfo.getPort()); String url = "/" + request.getTargetServiceUniqueName() + "/" + request.getMethodName(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("send request to url :{}", url); } // Create a simple POST request with a body. FullHttpRequest httpRequest = new DefaultFullHttpRequest(HTTP_1_1, POST, url, wrappedBuffer(request.getData().array())); HttpHeaders headers = httpRequest.headers(); addToHeader(headers, HttpHeaderNames.HOST, hostName); addToHeader(headers, HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name()); addToHeader(headers, HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); addToHeader(headers, HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); addToHeader(headers, RemotingConstants.HEAD_SERIALIZE_TYPE, SerializerFactory.getAliasByCode(request.getSerializeType())); addToHeader(headers, RemotingConstants.HEAD_TARGET_APP, request.getTargetAppName()); Map<String, Object> requestProps = request.getRequestProps(); if (requestProps != null) { // <String, Object> 转扁平化 <String, String> flatCopyTo("", requestProps, headers); } return httpRequest; }
Example #9
Source File: RpcSofaTracer.java From sofa-rpc with Apache License 2.0 | 6 votes |
private void generateClientErrorContext(Map<String, String> context, SofaRequest request, SofaTracerSpan clientSpan) { Map<String, String> tagsWithStr = clientSpan.getTagsWithStr(); //记录的上下文信息// do not change this key context.put("serviceName", tagsWithStr.get(RpcSpanTags.SERVICE)); context.put("methodName", tagsWithStr.get(RpcSpanTags.METHOD)); context.put("protocol", tagsWithStr.get(RpcSpanTags.PROTOCOL)); context.put("invokeType", tagsWithStr.get(RpcSpanTags.INVOKE_TYPE)); context.put("targetUrl", tagsWithStr.get(RpcSpanTags.REMOTE_IP)); context.put("targetApp", tagsWithStr.get(RpcSpanTags.REMOTE_APP)); context.put("targetZone", tagsWithStr.get(RpcSpanTags.REMOTE_ZONE)); context.put("targetIdc", tagsWithStr.get(RpcSpanTags.REMOTE_IDC)); context.put("paramTypes", com.alipay.common.tracer.core.utils.StringUtils.arrayToString(request.getMethodArgSigs(), '|', "", "")); context.put("targetCity", tagsWithStr.get(RpcSpanTags.REMOTE_CITY)); context.put("uid", tagsWithStr.get(RpcSpanTags.USER_ID)); }
Example #10
Source File: RpcSofaTracer.java From sofa-rpc with Apache License 2.0 | 6 votes |
private void generateServerErrorContext(Map<String, String> context, SofaRequest request, SofaTracerSpan serverSpan) { //tags Map<String, String> tagsWithStr = serverSpan.getTagsWithStr(); context.put("serviceName", tagsWithStr.get(RpcSpanTags.SERVICE)); context.put("methodName", tagsWithStr.get(RpcSpanTags.METHOD)); context.put("protocol", tagsWithStr.get(RpcSpanTags.PROTOCOL)); context.put("invokeType", tagsWithStr.get(RpcSpanTags.INVOKE_TYPE)); context.put("callerUrl", tagsWithStr.get(RpcSpanTags.REMOTE_IP)); context.put("callerApp", tagsWithStr.get(RpcSpanTags.REMOTE_APP)); context.put("callerZone", tagsWithStr.get(RpcSpanTags.REMOTE_ZONE)); context.put("callerIdc", tagsWithStr.get(RpcSpanTags.REMOTE_IDC)); //paramTypes if (request != null) { context.put("paramTypes", com.alipay.common.tracer.core.utils.StringUtils .arrayToString(request.getMethodArgSigs(), '|', "", "")); } }
Example #11
Source File: SofaRpcSerialization.java From sofa-rpc with Apache License 2.0 | 6 votes |
protected void putRequestMetadataToHeader(Object requestObject, Map<String, String> header) { if (requestObject instanceof RequestBase) { RequestBase requestBase = (RequestBase) requestObject; header.put(RemotingConstants.HEAD_METHOD_NAME, requestBase.getMethodName()); header.put(RemotingConstants.HEAD_TARGET_SERVICE, requestBase.getTargetServiceUniqueName()); if (requestBase instanceof SofaRequest) { SofaRequest sofaRequest = (SofaRequest) requestBase; header.put(RemotingConstants.HEAD_TARGET_APP, sofaRequest.getTargetAppName()); Map<String, Object> requestProps = sofaRequest.getRequestProps(); if (requestProps != null) { // <String, Object> 转扁平化 <String, String> CodecUtils.flatCopyTo("", requestProps, header); } } } }
Example #12
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 #13
Source File: ProtostuffSerializer.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public AbstractByteBuf encode(Object object, Map<String, String> context) throws SofaRpcException { if (object == null) { throw buildSerializeError("Unsupported null message!"); } else if (object instanceof SofaRequest) { return encodeSofaRequest((SofaRequest) object, context); } else if (object instanceof SofaResponse) { return encodeSofaResponse((SofaResponse) object, context); } else { Class clazz = object.getClass(); Schema schema = RuntimeSchema.getSchema(clazz); // Re-use (manage) this buffer to avoid allocating on every serialization LinkedBuffer buffer = LinkedBuffer.allocate(512); // ser try { return new ByteArrayWrapperByteBuf(ProtostuffIOUtil.toByteArray(object, schema, buffer)); } finally { buffer.clear(); } } }
Example #14
Source File: AbstractLoadBalancer.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Override public ProviderInfo select(SofaRequest request, List<ProviderInfo> providerInfos) throws SofaRpcException { if (providerInfos.size() == 0) { throw noAvailableProviderException(request.getTargetServiceUniqueName()); } if (providerInfos.size() == 1) { return providerInfos.get(0); } else { return doSelect(request, providerInfos); } }
Example #15
Source File: SofaRequestHessianSerializer.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Override public AbstractByteBuf encodeObject(SofaRequest sofaRequest, Map<String, String> context) { try { UnsafeByteArrayOutputStream outputStream = new UnsafeByteArrayOutputStream(); Hessian2Output output = new Hessian2Output(outputStream); // 根据SerializeType信息决定序列化器 boolean genericSerialize = context != null && isGenericRequest(context.get(RemotingConstants.HEAD_GENERIC_TYPE)); if (genericSerialize) { output.setSerializerFactory(genericSerializerFactory); } else { output.setSerializerFactory(serializerFactory); } output.writeObject(sofaRequest); final Object[] args = sofaRequest.getMethodArgs(); if (args != null) { for (Object arg : args) { output.writeObject(arg); } } output.close(); return new ByteStreamWrapperByteBuf(outputStream); } catch (IOException e) { throw buildSerializeError(e.getMessage(), e); } }
Example #16
Source File: HttpServerHandler.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * Handle request from HTTP/1.1 * * @param request SofaRequest * @param ctx ChannelHandlerContext * @param keepAlive keepAlive */ public void handleHttp1Request(SofaRequest request, ChannelHandlerContext ctx, boolean keepAlive) { Http1ServerTask task = new Http1ServerTask(this, request, ctx, keepAlive); processingCount.incrementAndGet(); try { task.run(); } catch (RejectedExecutionException e) { processingCount.decrementAndGet(); throw e; } }
Example #17
Source File: MeshRouter.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Override public List<ProviderInfo> route(SofaRequest request, List<ProviderInfo> providerInfos) { AddressHolder addressHolder = consumerBootstrap.getCluster().getAddressHolder(); if (addressHolder != null) { List<ProviderInfo> current = addressHolder.getProviderInfos(RpcConstants.ADDRESS_DEFAULT_GROUP); if (providerInfos != null) { providerInfos.addAll(current); } else { providerInfos = current; } } recordRouterWay(RPC_MESH_ROUTER); return providerInfos; }
Example #18
Source File: SofaHessianSerializer.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * Instantiates a new Sofa hessian serializer. */ public SofaHessianSerializer() { try { ClassUtils.forName("com.caucho.hessian.io.ShortHandle"); if (LOGGER.isInfoEnabled()) { LOGGER.info("Version of sofa-hessian is v4.x"); } } catch (Exception e) { if (LOGGER.isInfoEnabled()) { LOGGER.info("Version of sofa-hessian is v3.x"); } } boolean enableMultipleClassLoader = RpcConfigs.getBooleanValue(RpcOptions.MULTIPLE_CLASSLOADER_ENABLE); serializerFactory = getSerializerFactory(enableMultipleClassLoader, false); genericSerializerFactory = getSerializerFactory(enableMultipleClassLoader, true); if (RpcConfigs.getBooleanValue(RpcOptions.SERIALIZE_BLACKLIST_ENABLE) && SofaConfigs.getBooleanValue(SofaOptions.CONFIG_SERIALIZE_BLACKLIST, true)) { ClassNameResolver resolver = new ClassNameResolver(); resolver.addFilter(new NameBlackListFilter(BlackListFileLoader.SOFA_SERIALIZE_BLACK_LIST, 8192)); serializerFactory.setClassNameResolver(resolver); genericSerializerFactory.setClassNameResolver(resolver); } else { serializerFactory.setClassNameResolver(null); genericSerializerFactory.setClassNameResolver(null); } CustomHessianSerializerManager.addSerializer(SofaRequest.class, new SofaRequestHessianSerializer(serializerFactory, genericSerializerFactory)); CustomHessianSerializerManager.addSerializer(SofaResponse.class, new SofaResponseHessianSerializer(serializerFactory, genericSerializerFactory)); }
Example #19
Source File: AbstractCluster.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * 决定超时时间 * * @param request 请求 * @param consumerConfig 客户端配置 * @param providerInfo 服务提供者信息 * @return 调用超时 */ private int resolveTimeout(SofaRequest request, ConsumerConfig consumerConfig, ProviderInfo providerInfo) { // 动态配置优先 final String dynamicAlias = consumerConfig.getParameter(DynamicConfigKeys.DYNAMIC_ALIAS); if (StringUtils.isNotBlank(dynamicAlias)) { String dynamicTimeout = null; DynamicConfigManager dynamicConfigManager = DynamicConfigManagerFactory.getDynamicManager( consumerConfig.getAppName(), dynamicAlias); if (dynamicConfigManager != null) { dynamicTimeout = dynamicConfigManager.getConsumerMethodProperty(request.getInterfaceName(), request.getMethodName(), "timeout"); } if (DynamicHelper.isNotDefault(dynamicTimeout) && StringUtils.isNotBlank(dynamicTimeout)) { return Integer.parseInt(dynamicTimeout); } } // 先去调用级别配置 Integer timeout = request.getTimeout(); if (timeout == null) { // 取客户端配置(先方法级别再接口级别) timeout = consumerConfig.getMethodTimeout(request.getMethodName()); if (timeout == null || timeout < 0) { // 再取服务端配置 timeout = (Integer) providerInfo.getDynamicAttr(ATTR_TIMEOUT); if (timeout == null) { // 取框架默认值 timeout = getIntValue(CONSUMER_INVOKE_TIMEOUT); } } } return timeout; }
Example #20
Source File: JacksonSerializerTest.java From sofa-rpc with Apache License 2.0 | 5 votes |
private SofaRequest buildSay3Request() throws NoSuchMethodException { final DemoRequest demoRequest = new DemoRequest(); demoRequest.setName("name"); List<DemoRequest> list = new ArrayList<DemoRequest>(); list.add(demoRequest); return buildRequest("say3", new Object[] { list }); }
Example #21
Source File: HttpServerHandler.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * Handle request from HTTP/2 * * @param streamId stream Id * @param request SofaRequest * @param ctx ChannelHandlerContext * @param encoder Http2ConnectionEncoder */ public void handleHttp2Request(int streamId, SofaRequest request, ChannelHandlerContext ctx, Http2ConnectionEncoder encoder) { Http2ServerTask task = new Http2ServerTask(this, request, ctx, streamId, encoder); processingCount.incrementAndGet(); try { task.run(); } catch (RejectedExecutionException e) { processingCount.decrementAndGet(); throw e; } }
Example #22
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 #23
Source File: BaggageResolver.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * 通过请求透传数据 * * @param context RpcInvokeContext * @param request 请求 */ public static void carryWithRequest(RpcInvokeContext context, SofaRequest request) { if (context != null) { Map<String, String> requestBaggage = context.getAllRequestBaggage(); if (CommonUtils.isNotEmpty(requestBaggage)) { // 需要透传 request.addRequestProp(RemotingConstants.RPC_REQUEST_BAGGAGE, requestBaggage); } } }
Example #24
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 #25
Source File: ProviderBaggageFilter.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Override public SofaResponse invoke(FilterInvoker invoker, SofaRequest request) throws SofaRpcException { SofaResponse response = null; try { BaggageResolver.pickupFromRequest(RpcInvokeContext.peekContext(), request, true); response = invoker.invoke(request); } finally { if (response != null) { BaggageResolver.carryWithResponse(RpcInvokeContext.peekContext(), response); } } return response; }
Example #26
Source File: AbstractHttpClientHandler.java From sofa-rpc with Apache License 2.0 | 5 votes |
protected AbstractHttpClientHandler(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 #27
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 #28
Source File: ProtostuffSerializer.java From sofa-rpc with Apache License 2.0 | 5 votes |
private void parseRequestHeader(String key, Map<String, String> headerMap, SofaRequest sofaRequest) { Map<String, String> traceMap = new HashMap<String, String>(8); CodecUtils.treeCopyTo(key + ".", headerMap, traceMap, true); if (!traceMap.isEmpty()) { sofaRequest.addRequestProp(key, traceMap); } }
Example #29
Source File: Tracers.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * 1.1. 客户端异步发送后 * * @param request 请求 */ public static void clientAsyncAfterSend(SofaRequest request) { if (openTrace) { try { tracer.clientAsyncAfterSend(request); } catch (Exception e) { if (LOGGER.isWarnEnabled()) { LOGGER.warn(e.getMessage(), e); } } } }
Example #30
Source File: ClientSyncReceiveEvent.java From sofa-rpc with Apache License 2.0 | 5 votes |
public ClientSyncReceiveEvent(ConsumerConfig consumerConfig, ProviderInfo providerInfo, SofaRequest request, SofaResponse response, Throwable throwable) { this.consumerConfig = consumerConfig; this.providerInfo = providerInfo; this.request = request; this.response = response; this.throwable = throwable; }