Search in sources :

Example 26 with Response

use of com.weibo.api.motan.rpc.Response in project motan by weibocom.

the class YarProtocolUtilTest method testConvertYarResponse.

@Test
public void testConvertYarResponse() {
    DefaultResponse response = new DefaultResponse();
    response.setRequestId(456);
    response.setValue("stringValue");
    YarResponse yarResponse = YarProtocolUtil.convert(response, "JSON");
    assertNotNull(yarResponse);
    Response newResponse = YarProtocolUtil.convert(yarResponse);
    assertEquals(response.getRequestId(), newResponse.getRequestId());
    assertEquals(response.getValue(), newResponse.getValue());
    response.setException(new RuntimeException("test exception"));
    yarResponse = YarProtocolUtil.convert(response, "JSON");
    assertNotNull(yarResponse);
    newResponse = YarProtocolUtil.convert(yarResponse);
    assertEquals(response.getRequestId(), newResponse.getRequestId());
    // yarresponse的异常会转为motan业务异常
    assertEquals(new MotanBizException(response.getException().getMessage()).getMessage(), newResponse.getException().getMessage());
}
Also used : DefaultResponse(com.weibo.api.motan.rpc.DefaultResponse) YarResponse(com.weibo.yar.YarResponse) DefaultResponse(com.weibo.api.motan.rpc.DefaultResponse) Response(com.weibo.api.motan.rpc.Response) YarResponse(com.weibo.yar.YarResponse) MotanBizException(com.weibo.api.motan.exception.MotanBizException) Test(org.junit.Test)

Example 27 with Response

use of com.weibo.api.motan.rpc.Response in project motan by weibocom.

the class NettyClient method initClientBootstrap.

/**
	 * 初始化 netty clientBootstrap
	 */
private void initClientBootstrap() {
    bootstrap = new ClientBootstrap(channelFactory);
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    // 实际上,极端情况下,connectTimeout会达到500ms,因为netty nio的实现中,是依赖BossThread来控制超时,
    // 如果为了严格意义的timeout,那么需要应用端进行控制。
    int timeout = getUrl().getIntParameter(URLParamType.connectTimeout.getName(), URLParamType.connectTimeout.getIntValue());
    if (timeout <= 0) {
        throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
    }
    bootstrap.setOption("connectTimeoutMillis", timeout);
    // 最大响应包限制
    final int maxContentLength = url.getIntParameter(URLParamType.maxContentLength.getName(), URLParamType.maxContentLength.getIntValue());
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

        public ChannelPipeline getPipeline() {
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", new NettyDecoder(codec, NettyClient.this, maxContentLength));
            pipeline.addLast("encoder", new NettyEncoder(codec, NettyClient.this));
            pipeline.addLast("handler", new NettyChannelHandler(NettyClient.this, new MessageHandler() {

                @Override
                public Object handle(Channel channel, Object message) {
                    Response response = (Response) message;
                    NettyResponseFuture responseFuture = NettyClient.this.removeCallback(response.getRequestId());
                    if (responseFuture == null) {
                        LoggerUtil.warn("NettyClient has response from server, but resonseFuture not exist,  requestId={}", response.getRequestId());
                        return null;
                    }
                    if (response.getException() != null) {
                        responseFuture.onFailure(response);
                    } else {
                        responseFuture.onSuccess(response);
                    }
                    return null;
                }
            }));
            return pipeline;
        }
    });
}
Also used : MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) MessageHandler(com.weibo.api.motan.transport.MessageHandler) Channel(com.weibo.api.motan.transport.Channel) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) DefaultResponse(com.weibo.api.motan.rpc.DefaultResponse) Response(com.weibo.api.motan.rpc.Response) ClientBootstrap(org.jboss.netty.bootstrap.ClientBootstrap) ChannelPipelineFactory(org.jboss.netty.channel.ChannelPipelineFactory)

Example 28 with Response

use of com.weibo.api.motan.rpc.Response in project motan by weibocom.

the class NettyDecoder method decode.

@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
    if (buffer.readableBytes() <= MotanConstants.NETTY_HEADER) {
        return null;
    }
    buffer.markReaderIndex();
    short type = buffer.readShort();
    if (type != MotanConstants.NETTY_MAGIC_TYPE) {
        buffer.resetReaderIndex();
        throw new MotanFrameworkException("NettyDecoder transport header not support, type: " + type);
    }
    byte messageType = (byte) buffer.readShort();
    long requestId = buffer.readLong();
    int dataLength = buffer.readInt();
    // FIXME 如果dataLength过大,可能导致问题
    if (buffer.readableBytes() < dataLength) {
        buffer.resetReaderIndex();
        return null;
    }
    if (maxContentLength > 0 && dataLength > maxContentLength) {
        LoggerUtil.warn("NettyDecoder transport data content length over of limit, size: {}  > {}. remote={} local={}", dataLength, maxContentLength, ctx.getChannel().getRemoteAddress(), ctx.getChannel().getLocalAddress());
        Exception e = new MotanServiceException("NettyDecoder transport data content length over of limit, size: " + dataLength + " > " + maxContentLength);
        if (messageType == MotanConstants.FLAG_REQUEST) {
            Response response = buildExceptionResponse(requestId, e);
            channel.write(response);
            throw e;
        } else {
            throw e;
        }
    }
    byte[] data = new byte[dataLength];
    buffer.readBytes(data);
    try {
        String remoteIp = getRemoteIp(channel);
        return codec.decode(client, remoteIp, data);
    } catch (Exception e) {
        if (messageType == MotanConstants.FLAG_REQUEST) {
            Response resonse = buildExceptionResponse(requestId, e);
            channel.write(resonse);
            return null;
        } else {
            Response resonse = buildExceptionResponse(requestId, e);
            return resonse;
        }
    }
}
Also used : DefaultResponse(com.weibo.api.motan.rpc.DefaultResponse) Response(com.weibo.api.motan.rpc.Response) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException)

Example 29 with Response

use of com.weibo.api.motan.rpc.Response in project motan by weibocom.

the class ProtocolFilterDecorator method decorateWithFilter.

private <T> Referer<T> decorateWithFilter(Referer<T> referer, URL url) {
    List<Filter> filters = getFilters(url, MotanConstants.NODE_TYPE_REFERER);
    Referer<T> lastRef = referer;
    for (Filter filter : filters) {
        final Filter f = filter;
        final Referer<T> lf = lastRef;
        lastRef = new Referer<T>() {

            @Override
            public Response call(Request request) {
                Activation activation = f.getClass().getAnnotation(Activation.class);
                if (activation != null && !activation.retry() && request.getRetries() != 0) {
                    return lf.call(request);
                }
                return f.filter(lf, request);
            }

            @Override
            public String desc() {
                return lf.desc();
            }

            @Override
            public void destroy() {
                lf.destroy();
            }

            @Override
            public Class<T> getInterface() {
                return lf.getInterface();
            }

            @Override
            public URL getUrl() {
                return lf.getUrl();
            }

            @Override
            public void init() {
                lf.init();
            }

            @Override
            public boolean isAvailable() {
                return lf.isAvailable();
            }

            @Override
            public int activeRefererCount() {
                return lf.activeRefererCount();
            }

            @Override
            public URL getServiceUrl() {
                return lf.getServiceUrl();
            }
        };
    }
    return lastRef;
}
Also used : Response(com.weibo.api.motan.rpc.Response) Filter(com.weibo.api.motan.filter.Filter) AccessLogFilter(com.weibo.api.motan.filter.AccessLogFilter) Request(com.weibo.api.motan.rpc.Request) Activation(com.weibo.api.motan.core.extension.Activation) URL(com.weibo.api.motan.rpc.URL)

Example 30 with Response

use of com.weibo.api.motan.rpc.Response in project motan by weibocom.

the class AccessLogFilter method filter.

@Override
public Response filter(Caller<?> caller, Request request) {
    boolean needLog = caller.getUrl().getBooleanParameter(URLParamType.accessLog.getName(), URLParamType.accessLog.getBooleanValue());
    if (needLog) {
        long t1 = System.currentTimeMillis();
        boolean success = false;
        try {
            Response response = caller.call(request);
            success = true;
            return response;
        } finally {
            long consumeTime = System.currentTimeMillis() - t1;
            logAccess(caller, request, consumeTime, success);
        }
    } else {
        return caller.call(request);
    }
}
Also used : Response(com.weibo.api.motan.rpc.Response)

Aggregations

Response (com.weibo.api.motan.rpc.Response)31 URL (com.weibo.api.motan.rpc.URL)13 MotanServiceException (com.weibo.api.motan.exception.MotanServiceException)11 DefaultResponse (com.weibo.api.motan.rpc.DefaultResponse)11 Request (com.weibo.api.motan.rpc.Request)11 Expectations (org.jmock.Expectations)10 Test (org.junit.Test)9 DefaultRequest (com.weibo.api.motan.rpc.DefaultRequest)7 IHello (com.weibo.api.motan.protocol.example.IHello)6 MotanFrameworkException (com.weibo.api.motan.exception.MotanFrameworkException)4 IWorld (com.weibo.api.motan.protocol.example.IWorld)4 Referer (com.weibo.api.motan.rpc.Referer)4 RegistryService (com.weibo.api.motan.registry.RegistryService)3 HashMap (java.util.HashMap)3 MotanBizException (com.weibo.api.motan.exception.MotanBizException)2 AccessLogFilter (com.weibo.api.motan.filter.AccessLogFilter)2 Filter (com.weibo.api.motan.filter.Filter)2 Channel (com.weibo.api.motan.transport.Channel)2 YarResponse (com.weibo.yar.YarResponse)2 MockTracer (io.opentracing.mock.MockTracer)2