Search in sources :

Example 1 with RpcClient

use of com.baidu.brpc.client.RpcClient 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 RpcClient

use of com.baidu.brpc.client.RpcClient in project brpc-java by baidu.

the class SingleConnectionClientTest method main.

public static void main(String[] args) {
    String serviceUrl = "list://127.0.0.1:8002";
    List<Interceptor> interceptors = Lists.newArrayList();
    RpcClient rpcClient = new RpcClient(serviceUrl, getRpcClientOptions(), interceptors);
    // build request
    final Echo.EchoRequest request = Echo.EchoRequest.newBuilder().setMessage("test single connection").build();
    // sync call
    final EchoService echoService = BrpcProxy.getProxy(rpcClient, EchoService.class);
    ScheduledExecutorService schedule = Executors.newScheduledThreadPool(10);
    final AtomicInteger counter = new AtomicInteger(0);
    final Random random = new Random(System.currentTimeMillis());
    schedule.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            try {
                int index = counter.getAndIncrement();
                int countInHalfMinute = 30 * 1000000 / PERIOD;
                if (((index / countInHalfMinute) & 1) == 1) {
                    return;
                }
                RpcContext rpcContext = RpcContext.getContext();
                rpcContext.setRequestBinaryAttachment("example attachment".getBytes());
                Echo.EchoResponse response = echoService.echo(request);
                // sample log
                if (random.nextInt(10000) < 30) {
                    LOG.info("sync call service=EchoService.echo success, " + "request={},response={}", request.getMessage(), response.getMessage());
                }
                rpcContext = RpcContext.getContext();
                if (rpcContext.getResponseBinaryAttachment() != null) {
                    LOG.info("attachment=" + new String(rpcContext.getResponseBinaryAttachment().array()));
                    ReferenceCountUtil.release(rpcContext.getResponseBinaryAttachment());
                }
            } catch (RpcException ex) {
                if (random.nextInt(10000) < 30) {
                    LOG.error("sync call failed, ex=" + ex.getMessage());
                }
            } catch (Exception e) {
                LOG.info("other exception, {}", e);
            }
        }
    }, 100000, PERIOD, TimeUnit.MICROSECONDS);
    while (counter.get() < 1000000) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        LOG.info("count:{}", counter.get());
    }
    schedule.shutdown();
    rpcClient.stop();
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) RpcException(com.baidu.brpc.exceptions.RpcException) RpcContext(com.baidu.brpc.RpcContext) Random(java.util.Random) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RpcException(com.baidu.brpc.exceptions.RpcException) Interceptor(com.baidu.brpc.interceptor.Interceptor) RpcClient(com.baidu.brpc.client.RpcClient)

Example 3 with RpcClient

use of com.baidu.brpc.client.RpcClient in project brpc-java by baidu.

the class SyncBenchmarkTest method main.

public static void main(String[] args) throws InterruptedException, IOException {
    if (args.length != 2) {
        System.out.println("usage: BenchmarkTest list://127.0.0.1:8002 threadNum");
        System.exit(-1);
    }
    RpcClientOptions options = new RpcClientOptions();
    options.setProtocolType(Options.ProtocolType.PROTOCOL_BAIDU_STD_VALUE);
    options.setLoadBalanceType(LoadBalanceStrategy.LOAD_BALANCE_FAIR);
    options.setMaxTotalConnections(1000000);
    options.setMinIdleConnections(10);
    options.setConnectTimeoutMillis(100);
    options.setWriteTimeoutMillis(100);
    options.setReadTimeoutMillis(100);
    options.setTcpNoDelay(false);
    options.setMaxTryTimes(1);
    options.setChannelType(ChannelType.SINGLE_CONNECTION);
    RpcClient rpcClient = new RpcClient(args[0], options, null);
    int threadNum = Integer.parseInt(args[1]);
    InputStream inputStream = Thread.currentThread().getClass().getResourceAsStream("/message.txt");
    int length = inputStream.available();
    byte[] messageBytes = new byte[length];
    inputStream.read(messageBytes);
    log.info("message size=" + messageBytes.length);
    EchoService echoService = BrpcProxy.getProxy(rpcClient, EchoService.class);
    SendInfo[] sendInfos = new SendInfo[threadNum];
    Thread[] threads = new Thread[threadNum];
    for (int i = 0; i < threadNum; i++) {
        sendInfos[i] = new SendInfo();
        threads[i] = new Thread(new ThreadTask(i, rpcClient, messageBytes, sendInfos[i], echoService), "work-thread-" + i);
        threads[i].start();
    }
    long lastSuccessRequestNum = 0;
    long lastFailRequestNum = 0;
    long lastElapsedNs = 0;
    while (!stop) {
        long beginTime = System.nanoTime();
        try {
            Thread.sleep(1000);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        long successNum = 0;
        long failNum = 0;
        long elapseNs = 0;
        long averageElapsedNs = 0;
        for (SendInfo sendInfo : sendInfos) {
            successNum += sendInfo.successRequestNum;
            failNum += sendInfo.failRequestNum;
            elapseNs += sendInfo.elapsedNs;
        }
        if (successNum - lastSuccessRequestNum > 0) {
            averageElapsedNs = (elapseNs - lastElapsedNs) / (successNum - lastSuccessRequestNum);
        }
        long endTime = System.nanoTime();
        log.info("success={},fail={},average={}ns", (successNum - lastSuccessRequestNum) * 1000 * 1000 * 1000 / (endTime - beginTime), (failNum - lastFailRequestNum) * 1000 * 1000 * 1000 / (endTime - beginTime), averageElapsedNs);
        lastSuccessRequestNum = successNum;
        lastFailRequestNum = failNum;
        lastElapsedNs = elapseNs;
    }
}
Also used : RpcClientOptions(com.baidu.brpc.client.RpcClientOptions) InputStream(java.io.InputStream) IOException(java.io.IOException) RpcException(com.baidu.brpc.exceptions.RpcException) RpcClient(com.baidu.brpc.client.RpcClient)

Example 4 with RpcClient

use of com.baidu.brpc.client.RpcClient in project brpc-java by baidu.

the class StargateDemoClient method main.

public static void main(String[] args) {
    RpcClientOptions options = new RpcClientOptions();
    // Stargate 协议需要强指定协议类型,不可使用BRPC协议解析器
    options.setProtocolType(Options.ProtocolType.PROTOCOL_STARGATE_VALUE);
    options.setReadTimeoutMillis(1000);
    options.setWriteTimeoutMillis(1000);
    RpcClient rpcClient = new RpcClient(StargateDemoConstant.namingUrl, options);
    NamingOptions namingOptions = new NamingOptions();
    namingOptions.setGroup(StargateDemoConstant.group);
    namingOptions.setVersion(StargateDemoConstant.version);
    StargateDemoService proxy = BrpcProxy.getProxy(rpcClient, StargateDemoService.class, namingOptions);
    for (int i = 0, times = 10; i < times; i++) {
        RpcContext rpcContext = RpcContext.getContext();
        rpcContext.reset();
        rpcContext.setRequestKvAttachment("key", "value");
        StargateDemoReqDto reqDto = new StargateDemoReqDto();
        reqDto.setId(1000L);
        reqDto.setName("test");
        StargateDemoResDto call = proxy.call(reqDto);
        System.out.println(GsonUtils.toJson(call));
        if (rpcContext.getResponseKvAttachment() != null) {
            System.out.println(rpcContext.getResponseKvAttachment().get("resKey"));
        }
        System.out.println();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    rpcClient.stop();
}
Also used : RpcContext(com.baidu.brpc.RpcContext) RpcClientOptions(com.baidu.brpc.client.RpcClientOptions) NamingOptions(com.baidu.brpc.protocol.NamingOptions) RpcClient(com.baidu.brpc.client.RpcClient)

Example 5 with RpcClient

use of com.baidu.brpc.client.RpcClient in project brpc-java by baidu.

the class BenchmarkClientPushTest method main.

// rpc press: send pressure to RpcServerTest
// push & rpc press: send pressure to BenchmarkServerPushTest
public static void main(String[] args) {
    if (args.length != 2) {
        System.out.println("usage: server_ip:server_port threadNum");
        System.exit(-1);
    }
    RpcClientOptions clientOption = new RpcClientOptions();
    clientOption.setProtocolType(Options.ProtocolType.PROTOCOL_SERVER_PUSH_VALUE);
    clientOption.setWriteTimeoutMillis(1000);
    clientOption.setReadTimeoutMillis(1000);
    clientOption.setMaxTotalConnections(1000);
    // clientOption.setMaxTotalConnections(10);
    clientOption.setMinIdleConnections(100);
    clientOption.setLoadBalanceType(LoadBalanceStrategy.LOAD_BALANCE_FAIR);
    clientOption.setCompressType(Options.CompressType.COMPRESS_TYPE_NONE);
    clientOption.setClientName("Benchmark");
    int threadNum = Integer.parseInt(args[1]);
    String serviceUrl = args[0];
    // String serviceUrl = "list://127.0.0.1:8012";
    List<Interceptor> interceptors = new ArrayList<Interceptor>();
    interceptors.add(new CustomInterceptor());
    RpcClient rpcClient = new RpcClient(serviceUrl, clientOption);
    EchoServiceAsync echoService = BrpcProxy.getProxy(rpcClient, EchoServiceAsync.class);
    rpcClient.registerPushService(new UserPushApiImpl());
    byte[] messageBytes = null;
    try {
        InputStream inputStream = Thread.currentThread().getClass().getResourceAsStream("/message_1k.txt");
        int length = inputStream.available();
        messageBytes = new byte[length];
        inputStream.read(messageBytes);
    } catch (IOException ex) {
        System.exit(1);
    }
    SendInfo[] sendInfos = new SendInfo[threadNum];
    Thread[] threads = new Thread[threadNum];
    for (int i = 0; i < threadNum; i++) {
        sendInfos[i] = new SendInfo();
        threads[i] = new Thread(new ThreadTask(messageBytes, sendInfos[i], echoService), "Benchnark-" + i);
        threads[i].start();
    }
    long lastSuccessRequestNum = 0;
    long lastFailRequestNum = 0;
    long lastElapsedNs = 0;
    int second = 0;
    long skippedQps = 0;
    while (!stop) {
        long beginTime = System.nanoTime();
        try {
            Thread.sleep(1000);
            ++second;
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        long successNum = 0;
        long failNum = 0;
        long elapseNs = 0;
        long averageElapsedNs = 0;
        for (SendInfo sendInfo : sendInfos) {
            successNum += sendInfo.successRequestNum;
            failNum += sendInfo.failRequestNum;
            elapseNs += sendInfo.elapsedNs;
        }
        if (successNum - lastSuccessRequestNum > 0) {
            averageElapsedNs = (elapseNs - lastElapsedNs) / (successNum - lastSuccessRequestNum);
        }
        long endTime = System.nanoTime();
        String msg = String.format("success=%s,fail=%s,average=%sns", (successNum - lastSuccessRequestNum) * 1000 * 1000 * 1000 / (endTime - beginTime), (failNum - lastFailRequestNum) * 1000 * 1000 * 1000 / (endTime - beginTime), averageElapsedNs);
        lastSuccessRequestNum = successNum;
        lastFailRequestNum = failNum;
        lastElapsedNs = elapseNs;
        // 从第10开始计算平均qps
        if (second > 30) {
            long avgQps = (lastSuccessRequestNum - skippedQps) / (second - 30);
            msg = msg + ", avgQps=" + avgQps;
        } else {
            skippedQps = lastSuccessRequestNum;
        }
        log.info(msg);
    }
}
Also used : RpcClientOptions(com.baidu.brpc.client.RpcClientOptions) EchoServiceAsync(com.baidu.brpc.example.push.normal.EchoServiceAsync) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) IOException(java.io.IOException) CustomInterceptor(com.baidu.brpc.example.interceptor.CustomInterceptor) CustomInterceptor(com.baidu.brpc.example.interceptor.CustomInterceptor) Interceptor(com.baidu.brpc.interceptor.Interceptor) UserPushApiImpl(com.baidu.brpc.example.push.push.UserPushApiImpl) RpcClient(com.baidu.brpc.client.RpcClient)

Aggregations

RpcClient (com.baidu.brpc.client.RpcClient)31 RpcClientOptions (com.baidu.brpc.client.RpcClientOptions)24 RpcException (com.baidu.brpc.exceptions.RpcException)10 EchoService (com.baidu.brpc.protocol.standard.EchoService)9 Test (org.junit.Test)9 Interceptor (com.baidu.brpc.interceptor.Interceptor)8 Echo (com.baidu.brpc.protocol.standard.Echo)8 ArrayList (java.util.ArrayList)8 CustomInterceptor (com.baidu.brpc.example.interceptor.CustomInterceptor)7 RpcCallback (com.baidu.brpc.client.RpcCallback)6 IOException (java.io.IOException)5 InputStream (java.io.InputStream)5 NamingOptions (com.baidu.brpc.protocol.NamingOptions)4 RpcContext (com.baidu.brpc.RpcContext)3 EchoServiceImpl (com.baidu.brpc.protocol.standard.EchoServiceImpl)3 UserPushApiImpl (com.baidu.brpc.example.push.push.UserPushApiImpl)2 Echo (com.baidu.brpc.example.standard.Echo)2 EchoResponse (com.baidu.brpc.example.standard.Echo.EchoResponse)2 EchoService (com.baidu.brpc.example.standard.EchoService)2 EchoServiceAsync (com.baidu.brpc.example.standard.EchoServiceAsync)2