Search in sources :

Example 1 with RpcException

use of com.baidu.brpc.exceptions.RpcException in project skywalking-java by apache.

the class CaseController method brpc.

@RequestMapping("/brpc")
@ResponseBody
public String brpc() {
    RpcClientOptions clientOption = new RpcClientOptions();
    clientOption.setProtocolType(Options.ProtocolType.PROTOCOL_BAIDU_STD_VALUE);
    clientOption.setWriteTimeoutMillis(1000);
    clientOption.setReadTimeoutMillis(5000);
    clientOption.setMaxTotalConnections(1000);
    clientOption.setMinIdleConnections(10);
    clientOption.setLoadBalanceType(LoadBalanceStrategy.LOAD_BALANCE_FAIR);
    clientOption.setCompressType(Options.CompressType.COMPRESS_TYPE_NONE);
    String serviceUrl = "list://127.0.0.1:1118";
    Echo.EchoRequest request = Echo.EchoRequest.newBuilder().setMessage("helloooooooooooo").build();
    RpcClient rpcClient = new RpcClient(serviceUrl, clientOption);
    EchoService echoService = BrpcProxy.getProxy(rpcClient, EchoService.class);
    try {
        EchoResponse response = echoService.echo(request);
    } catch (RpcException ex) {
    }
    rpcClient.stop();
    return SUCCESS;
}
Also used : EchoResponse(org.apache.skywalking.apm.testcase.baidu.brpc.interfaces.Echo.EchoResponse) RpcClientOptions(com.baidu.brpc.client.RpcClientOptions) Echo(org.apache.skywalking.apm.testcase.baidu.brpc.interfaces.Echo) EchoService(org.apache.skywalking.apm.testcase.baidu.brpc.interfaces.EchoService) RpcException(com.baidu.brpc.exceptions.RpcException) RpcClient(com.baidu.brpc.client.RpcClient) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 2 with RpcException

use of com.baidu.brpc.exceptions.RpcException in project brpc-java by baidu.

the class DubboRpcProtocol method decodeRequest.

@Override
public Request decodeRequest(Object packet) throws Exception {
    Request request = new RpcRequest();
    DubboPacket dubboPacket = (DubboPacket) packet;
    request.setCorrelationId(dubboPacket.getHeader().getCorrelationId());
    // check if it is heartbeat request
    byte flag = dubboPacket.getHeader().getFlag();
    if ((flag & DubboConstants.FLAG_EVENT) != 0) {
        Object bodyObject = DubboPacket.decodeEventBody(dubboPacket.getBodyBuf());
        if (bodyObject == DubboConstants.HEARTBEAT_EVENT) {
            request.setHeartbeat(true);
        } else {
            throw new RpcException("request body not null for event");
        }
        return request;
    }
    try {
        DubboRequestBody dubboRequestBody = DubboRequestBody.decodeRequestBody(dubboPacket.getBodyBuf());
        request.setArgs(dubboRequestBody.getArguments());
        request.setMethodName(dubboRequestBody.getPath());
        request.setRpcMethodInfo(dubboRequestBody.getRpcMethodInfo());
        request.setTarget(dubboRequestBody.getRpcMethodInfo().getTarget());
        request.setTargetMethod(dubboRequestBody.getRpcMethodInfo().getMethod());
        if (dubboRequestBody.getAttachments().size() > 0) {
            Map<String, Object> attachments = new HashMap<String, Object>(dubboRequestBody.getAttachments().size());
            for (Map.Entry<String, String> entry : dubboRequestBody.getAttachments().entrySet()) {
                attachments.put(entry.getKey(), entry.getValue());
            }
            request.setKvAttachment(attachments);
        }
        return request;
    } catch (Exception e) {
        log.error("dubbo decodeRequest error at {} ", e.getMessage(), e);
        throw new RpcException("dubbo decodeRequest error", e);
    }
}
Also used : HashMap(java.util.HashMap) RpcException(com.baidu.brpc.exceptions.RpcException) TooBigDataException(com.baidu.brpc.exceptions.TooBigDataException) NotEnoughDataException(com.baidu.brpc.exceptions.NotEnoughDataException) BadSchemaException(com.baidu.brpc.exceptions.BadSchemaException) RpcException(com.baidu.brpc.exceptions.RpcException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with RpcException

use of com.baidu.brpc.exceptions.RpcException in project brpc-java by baidu.

the class HttpRpcServlet method doPost.

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    long startTime = System.nanoTime();
    String requestUri = req.getRequestURI();
    if (requestUri == null) {
        LOG.warn("invalid request");
        resp.setStatus(404);
        return;
    }
    String encoding = req.getCharacterEncoding();
    String contentType = req.getContentType().split(";")[0];
    if (contentType == null) {
        contentType = "application/baidu.json-rpc";
    } else {
        contentType = contentType.toLowerCase();
    }
    byte[] bytes = this.readStream(req.getInputStream(), req.getContentLength());
    FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, requestUri);
    httpRequest.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);
    httpRequest.content().writeBytes(bytes);
    int protocolType = HttpRpcProtocol.parseProtocolType(contentType);
    CommunicationSpiManager.getInstance().loadAllExtensions(encoding);
    Protocol protocol = ProtocolManager.getInstance().getProtocol(protocolType);
    Request request = null;
    Response response = new HttpResponse();
    String errorMsg = null;
    try {
        request = protocol.decodeRequest(httpRequest);
        Object result = request.getTargetMethod().invoke(request.getTarget(), request.getArgs());
        response.setResult(result);
        response.setRpcMethodInfo(request.getRpcMethodInfo());
        response.setLogId(request.getLogId());
        response.setCorrelationId(request.getCorrelationId());
        protocol.encodeResponse(request, response);
    } catch (Exception ex) {
        errorMsg = String.format("invoke method failed, msg=%s", ex.getMessage());
        LOG.error(errorMsg);
        response.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errorMsg));
    }
    resp.setContentType(contentType);
    resp.setCharacterEncoding(encoding);
    if (errorMsg == null) {
        byte[] content = ((HttpRpcProtocol) protocol).encodeResponseBody(protocolType, request, response);
        resp.setContentLength(content.length);
        resp.getOutputStream().write(content);
    } else {
        byte[] content = errorMsg.getBytes();
        resp.setContentLength(content.length);
        resp.getOutputStream().write(content);
    }
    if (request != null) {
        long endTime = System.nanoTime();
        LOG.debug("uri={} logId={} service={} method={} elapseNs={}", requestUri, request.getLogId(), request.getTarget().getClass().getSimpleName(), request.getTargetMethod().getName(), endTime - startTime);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpResponse(com.baidu.brpc.protocol.HttpResponse) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) RpcException(com.baidu.brpc.exceptions.RpcException) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpResponse(com.baidu.brpc.protocol.HttpResponse) RpcException(com.baidu.brpc.exceptions.RpcException)

Example 4 with RpcException

use of com.baidu.brpc.exceptions.RpcException in project brpc-java by baidu.

the class HuluRpcProtocol method decodeRequest.

@Override
public Request decodeRequest(Object packet) throws Exception {
    Request request = this.createRequest();
    HuluRpcDecodePacket requestPacket = (HuluRpcDecodePacket) packet;
    ByteBuf metaBuf = requestPacket.getMetaBuf();
    ByteBuf protoAndAttachmentBuf = requestPacket.getProtoAndAttachmentBuf();
    ByteBuf protoBuf = null;
    try {
        HuluRpcProto.HuluRpcRequestMeta requestMeta = (HuluRpcProto.HuluRpcRequestMeta) ProtobufUtils.parseFrom(metaBuf, defaultRpcRequestMetaInstance);
        request.setCorrelationId(requestMeta.getCorrelationId());
        request.setLogId(requestMeta.getLogId());
        int compressType = requestMeta.getCompressType();
        request.setCompressType(compressType);
        // service info
        ServiceManager serviceManager = ServiceManager.getInstance();
        RpcMethodInfo rpcMethodInfo = serviceManager.getService(requestMeta.getServiceName(), String.valueOf(requestMeta.getMethodIndex()));
        if (rpcMethodInfo == null) {
            String errorMsg = String.format("Fail to find service=%s, methodIndex=%s", requestMeta.getServiceName(), requestMeta.getMethodIndex());
            request.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errorMsg));
            return request;
        }
        if (requestMeta.hasTraceId()) {
            request.setTraceId(requestMeta.getTraceId());
        }
        if (requestMeta.hasSpanId()) {
            request.setSpanId(request.getSpanId());
        }
        if (requestMeta.hasParentSpanId()) {
            request.setParentSpanId(requestMeta.getParentSpanId());
        }
        if (requestMeta.getExtFieldsCount() > 0) {
            if (request.getKvAttachment() == null) {
                request.setKvAttachment(new HashMap<String, Object>());
            }
            for (HuluRpcProto.HuluRpcRequestMetaExtField extField : requestMeta.getExtFieldsList()) {
                request.getKvAttachment().put(extField.getKey(), extField.getValue());
            }
        }
        request.setServiceName(rpcMethodInfo.getServiceName());
        request.setMethodName(rpcMethodInfo.getMethodName());
        request.setRpcMethodInfo(rpcMethodInfo);
        request.setTargetMethod(rpcMethodInfo.getMethod());
        request.setTarget(rpcMethodInfo.getTarget());
        // proto body
        try {
            Compress compress = compressManager.getCompress(compressType);
            int userMessageSize = requestMeta.getUserMessageSize();
            if (userMessageSize > 0) {
                protoBuf = protoAndAttachmentBuf.readSlice(userMessageSize);
            } else {
                protoBuf = protoAndAttachmentBuf;
            }
            Object requestProto = compress.uncompressInput(protoBuf, rpcMethodInfo);
            request.setArgs(new Object[] { requestProto });
            // attachment
            if (userMessageSize > 0) {
                request.setBinaryAttachment(protoAndAttachmentBuf);
                protoAndAttachmentBuf = null;
            }
        } catch (Exception ex) {
            String errorMsg = String.format("decode failed, msg=%s", ex.getMessage());
            LOG.error(errorMsg);
            throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, errorMsg, ex);
        }
        return request;
    } finally {
        if (metaBuf != null) {
            metaBuf.release();
        }
        if (protoAndAttachmentBuf != null) {
            protoAndAttachmentBuf.release();
        }
    }
}
Also used : Compress(com.baidu.brpc.compress.Compress) RpcMethodInfo(com.baidu.brpc.RpcMethodInfo) Request(com.baidu.brpc.protocol.Request) ByteBuf(io.netty.buffer.ByteBuf) DynamicCompositeByteBuf(com.baidu.brpc.buffer.DynamicCompositeByteBuf) RpcException(com.baidu.brpc.exceptions.RpcException) TooBigDataException(com.baidu.brpc.exceptions.TooBigDataException) NotEnoughDataException(com.baidu.brpc.exceptions.NotEnoughDataException) BadSchemaException(com.baidu.brpc.exceptions.BadSchemaException) IOException(java.io.IOException) ServiceManager(com.baidu.brpc.server.ServiceManager) RpcException(com.baidu.brpc.exceptions.RpcException)

Example 5 with RpcException

use of com.baidu.brpc.exceptions.RpcException in project brpc-java by baidu.

the class HuluRpcProtocol method encodeRequest.

@Override
public ByteBuf encodeRequest(Request request) throws Exception {
    HuluRpcEncodePacket requestPacket = new HuluRpcEncodePacket();
    HuluRpcProto.HuluRpcRequestMeta.Builder metaBuilder = HuluRpcProto.HuluRpcRequestMeta.newBuilder();
    metaBuilder.setCorrelationId(request.getCorrelationId());
    metaBuilder.setLogId(request.getLogId());
    int compressType = request.getCompressType();
    metaBuilder.setCompressType(compressType);
    // service method
    RpcMetaUtils.RpcMetaInfo rpcMetaInfo = RpcMetaUtils.parseRpcMeta(request.getTargetMethod());
    metaBuilder.setServiceName(rpcMetaInfo.getServiceName());
    try {
        int methodIndex = Integer.valueOf(rpcMetaInfo.getMethodName());
        metaBuilder.setMethodIndex(methodIndex);
    } catch (NumberFormatException ex) {
        String errorMsg = "methodName must be integer when using hulu rpc, " + "it is equal to proto method sequence from 0";
        LOG.warn(errorMsg);
        throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, errorMsg, ex);
    }
    if (request.getTraceId() != null) {
        metaBuilder.setTraceId(request.getTraceId());
    }
    if (request.getSpanId() != null) {
        metaBuilder.setSpanId(request.getSpanId());
    }
    if (request.getParentSpanId() != null) {
        metaBuilder.setSpanId(request.getParentSpanId());
    }
    if (request.getKvAttachment() != null) {
        for (Map.Entry<String, Object> kv : request.getKvAttachment().entrySet()) {
            metaBuilder.addExtFieldsBuilder().setKey(kv.getKey()).setValue((String) kv.getValue());
        }
    }
    // proto
    Object proto = request.getArgs()[0];
    Compress compress = compressManager.getCompress(compressType);
    ByteBuf protoBuf = compress.compressInput(proto, request.getRpcMethodInfo());
    requestPacket.setProto(protoBuf);
    // attachement
    if (request.getBinaryAttachment() != null && request.getBinaryAttachment().isReadable()) {
        requestPacket.setAttachment(request.getBinaryAttachment());
        metaBuilder.setUserMessageSize(protoBuf.readableBytes());
    }
    requestPacket.setRequestMeta(metaBuilder.build());
    return encode(requestPacket);
}
Also used : Compress(com.baidu.brpc.compress.Compress) RpcMetaUtils(com.baidu.brpc.utils.RpcMetaUtils) ByteBuf(io.netty.buffer.ByteBuf) DynamicCompositeByteBuf(com.baidu.brpc.buffer.DynamicCompositeByteBuf) RpcException(com.baidu.brpc.exceptions.RpcException) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

RpcException (com.baidu.brpc.exceptions.RpcException)68 ByteBuf (io.netty.buffer.ByteBuf)22 BadSchemaException (com.baidu.brpc.exceptions.BadSchemaException)20 NotEnoughDataException (com.baidu.brpc.exceptions.NotEnoughDataException)20 TooBigDataException (com.baidu.brpc.exceptions.TooBigDataException)20 DynamicCompositeByteBuf (com.baidu.brpc.buffer.DynamicCompositeByteBuf)16 ChannelInfo (com.baidu.brpc.ChannelInfo)13 ArrayList (java.util.ArrayList)12 Compress (com.baidu.brpc.compress.Compress)10 RpcMethodInfo (com.baidu.brpc.RpcMethodInfo)9 RpcClient (com.baidu.brpc.client.RpcClient)9 RpcFuture (com.baidu.brpc.client.RpcFuture)9 Request (com.baidu.brpc.protocol.Request)9 Interceptor (com.baidu.brpc.interceptor.Interceptor)8 Response (com.baidu.brpc.protocol.Response)8 RpcCallback (com.baidu.brpc.client.RpcCallback)7 RpcClientOptions (com.baidu.brpc.client.RpcClientOptions)7 RpcResponse (com.baidu.brpc.protocol.RpcResponse)7 HashMap (java.util.HashMap)7 Map (java.util.Map)7