Search in sources :

Example 1 with Interceptor

use of com.baidu.brpc.interceptor.Interceptor 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 2 with Interceptor

use of com.baidu.brpc.interceptor.Interceptor 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)

Example 3 with Interceptor

use of com.baidu.brpc.interceptor.Interceptor in project brpc-java by baidu.

the class RpcClientTest method main.

public static void main(String[] args) {
    RpcClientOptions clientOption = new RpcClientOptions();
    clientOption.setProtocolType(ProtocolType.PROTOCOL_HTTP_JSON_VALUE);
    clientOption.setWriteTimeoutMillis(1000);
    clientOption.setReadTimeoutMillis(30000);
    clientOption.setLoadBalanceType(LoadBalanceStrategy.LOAD_BALANCE_FAIR);
    clientOption.setMaxTryTimes(1);
    String serviceUrl = "list://127.0.0.1:8080";
    if (args.length == 1) {
        serviceUrl = args[0];
    }
    List<Interceptor> interceptors = new ArrayList<Interceptor>();
    interceptors.add(new CustomInterceptor());
    // sync call
    RpcClient rpcClient = new RpcClient(serviceUrl, clientOption, interceptors);
    EchoService echoService = BrpcProxy.getProxy(rpcClient, EchoService.class);
    try {
        String response = echoService.hello("okok");
        System.out.printf("sync call hello success, response=%s\n", response);
        response = echoService.hello2("jack", 123);
        System.out.printf("sync call hello2 success, response=%s\n", response);
        final Echo echoResp = echoService.hello3(new Echo("foo", new Date()));
        System.out.printf("sync call hello3 success, response=%s\n", echoResp);
    } catch (RpcException ex) {
        System.out.println("sync call failed, msg=" + ex.getMessage());
    }
    rpcClient.stop();
    // async call
    rpcClient = new RpcClient(serviceUrl, clientOption, interceptors);
    RpcCallback callback = new RpcCallback<String>() {

        @Override
        public void success(String response) {
            if (response != null) {
                System.out.printf("async call success, response=%s\n", response);
            } else {
                System.out.println("async call failed");
            }
        }

        @Override
        public void fail(Throwable e) {
            System.out.printf("async call failed, %s\n", e.getMessage());
        }
    };
    EchoServiceAsync echoServiceAsync = BrpcProxy.getProxy(rpcClient, EchoServiceAsync.class);
    try {
        Future<String> future = echoServiceAsync.hello("ok", callback);
        Future<String> future2 = echoServiceAsync.hello2("peter", 234, callback);
        try {
            if (future != null) {
                future.get();
            }
            if (future2 != null) {
                future2.get();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } catch (RpcException ex) {
        System.out.println("send exception, ex=" + ex.getMessage());
    }
    rpcClient.stop();
}
Also used : RpcClientOptions(com.baidu.brpc.client.RpcClientOptions) ArrayList(java.util.ArrayList) Date(java.util.Date) RpcException(com.baidu.brpc.exceptions.RpcException) CustomInterceptor(com.baidu.brpc.example.interceptor.CustomInterceptor) RpcException(com.baidu.brpc.exceptions.RpcException) RpcCallback(com.baidu.brpc.client.RpcCallback) CustomInterceptor(com.baidu.brpc.example.interceptor.CustomInterceptor) Interceptor(com.baidu.brpc.interceptor.Interceptor) RpcClient(com.baidu.brpc.client.RpcClient)

Example 4 with Interceptor

use of com.baidu.brpc.interceptor.Interceptor in project brpc-java by baidu.

the class ShortConnectionRpcClientTest method main.

public static void main(String[] args) {
    RpcClientOptions clientOption = new RpcClientOptions();
    clientOption.setProtocolType(ProtocolType.PROTOCOL_HTTP_JSON_VALUE);
    clientOption.setWriteTimeoutMillis(1000);
    clientOption.setReadTimeoutMillis(5000);
    clientOption.setLoadBalanceType(LoadBalanceStrategy.LOAD_BALANCE_FAIR);
    clientOption.setMaxTryTimes(1);
    clientOption.setChannelType(ChannelType.SHORT_CONNECTION);
    String serviceUrl = "list://127.0.0.1:8080";
    if (args.length == 1) {
        serviceUrl = args[0];
    }
    List<Interceptor> interceptors = new ArrayList<Interceptor>();
    ;
    interceptors.add(new CustomInterceptor());
    // sync call
    RpcClient rpcClient = new RpcClient(serviceUrl, clientOption, interceptors);
    EchoService echoService = BrpcProxy.getProxy(rpcClient, EchoService.class);
    try {
        String response = echoService.hello("okok");
        System.out.printf("sync call success, response=%s\n", response);
    } catch (RpcException ex) {
        System.out.println("sync call failed, msg=" + ex.getMessage());
    }
    rpcClient.stop();
    // async call
    rpcClient = new RpcClient(serviceUrl, clientOption, interceptors);
    RpcCallback callback = new RpcCallback<String>() {

        @Override
        public void success(String response) {
            if (response != null) {
                System.out.printf("async call success, response=%s\n", new Gson().toJson(response));
            } else {
                System.out.println("async call failed");
            }
        }

        @Override
        public void fail(Throwable e) {
            System.out.printf("async call failed, %s\n", e.getMessage());
        }
    };
    EchoServiceAsync echoServiceAsync = BrpcProxy.getProxy(rpcClient, EchoServiceAsync.class);
    try {
        Future<String> future = echoServiceAsync.hello("ok", callback);
        try {
            if (future != null) {
                future.get();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } catch (RpcException ex) {
        System.out.println("send exception, ex=" + ex.getMessage());
    }
    rpcClient.stop();
}
Also used : RpcClientOptions(com.baidu.brpc.client.RpcClientOptions) EchoServiceAsync(com.baidu.brpc.example.http.json.EchoServiceAsync) EchoService(com.baidu.brpc.example.http.json.EchoService) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) RpcException(com.baidu.brpc.exceptions.RpcException) CustomInterceptor(com.baidu.brpc.example.interceptor.CustomInterceptor) RpcException(com.baidu.brpc.exceptions.RpcException) RpcCallback(com.baidu.brpc.client.RpcCallback) CustomInterceptor(com.baidu.brpc.example.interceptor.CustomInterceptor) Interceptor(com.baidu.brpc.interceptor.Interceptor) RpcClient(com.baidu.brpc.client.RpcClient)

Example 5 with Interceptor

use of com.baidu.brpc.interceptor.Interceptor in project brpc-java by baidu.

the class SpringBootAnnotationResolver method createRpcProxyFactoryBean.

/**
 * Creates the rpc proxy factory bean.
 *
 * @return the rpc proxy factory bean
 */
private RpcProxyFactoryBean createRpcProxyFactoryBean(RpcProxy rpcProxy, DefaultListableBeanFactory beanFactory, Class serviceInterface) {
    GenericBeanDefinition beanDef = new GenericBeanDefinition();
    beanDef.setBeanClass(RpcProxyFactoryBean.class);
    beanDef.setDependsOn("brpcApplicationContextUtils");
    MutablePropertyValues values = new MutablePropertyValues();
    BrpcConfig brpcConfig = getServiceConfig(beanFactory, serviceInterface);
    for (Field field : RpcClientOptions.class.getDeclaredFields()) {
        try {
            if (field.getType().equals(Logger.class)) {
                // ignore properties of org.slf4j.Logger class
                continue;
            }
            field.setAccessible(true);
            values.addPropertyValue(field.getName(), field.get(brpcConfig.getClient()));
        } catch (Exception ex) {
            log.warn("field not exist:", ex);
        }
    }
    values.addPropertyValue("serviceInterface", serviceInterface);
    values.addPropertyValue("serviceId", rpcProxy.name());
    if (brpcConfig.getNaming() != null) {
        values.addPropertyValue("namingServiceUrl", brpcConfig.getNaming().getNamingServiceUrl());
        values.addPropertyValue("group", brpcConfig.getNaming().getGroup());
        values.addPropertyValue("version", brpcConfig.getNaming().getVersion());
        values.addPropertyValue("ignoreFailOfNamingService", brpcConfig.getNaming().isIgnoreFailOfNamingService());
    }
    // interceptor
    String interceptorNames = brpcConfig.getClient().getInterceptorBeanNames();
    if (!StringUtils.isBlank(interceptorNames)) {
        List<Interceptor> customInterceptors = new ArrayList<>();
        String[] interceptorNameArray = interceptorNames.split(",");
        for (String interceptorBeanName : interceptorNameArray) {
            Interceptor interceptor = beanFactory.getBean(interceptorBeanName, Interceptor.class);
            customInterceptors.add(interceptor);
        }
        values.addPropertyValue("interceptors", customInterceptors);
    }
    beanDef.setPropertyValues(values);
    String serviceInterfaceBeanName = serviceInterface.getSimpleName();
    beanFactory.registerBeanDefinition(serviceInterfaceBeanName, beanDef);
    return beanFactory.getBean("&" + serviceInterfaceBeanName, RpcProxyFactoryBean.class);
}
Also used : GenericBeanDefinition(org.springframework.beans.factory.support.GenericBeanDefinition) Field(java.lang.reflect.Field) MutablePropertyValues(org.springframework.beans.MutablePropertyValues) ArrayList(java.util.ArrayList) BrpcConfig(com.baidu.brpc.spring.boot.autoconfigure.config.BrpcConfig) Interceptor(com.baidu.brpc.interceptor.Interceptor) BeansException(org.springframework.beans.BeansException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException)

Aggregations

Interceptor (com.baidu.brpc.interceptor.Interceptor)17 ArrayList (java.util.ArrayList)14 RpcClient (com.baidu.brpc.client.RpcClient)8 RpcException (com.baidu.brpc.exceptions.RpcException)8 RpcCallback (com.baidu.brpc.client.RpcCallback)7 RpcClientOptions (com.baidu.brpc.client.RpcClientOptions)7 CustomInterceptor (com.baidu.brpc.example.interceptor.CustomInterceptor)7 RpcContext (com.baidu.brpc.RpcContext)3 RpcServer (com.baidu.brpc.server.RpcServer)3 BeansException (org.springframework.beans.BeansException)3 NoSuchBeanDefinitionException (org.springframework.beans.factory.NoSuchBeanDefinitionException)3 RpcServiceExporter (com.baidu.brpc.spring.RpcServiceExporter)2 BrpcConfig (com.baidu.brpc.spring.boot.autoconfigure.config.BrpcConfig)2 Field (java.lang.reflect.Field)2 BeforeClass (org.junit.BeforeClass)2 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)2 GenericBeanDefinition (org.springframework.beans.factory.support.GenericBeanDefinition)2 JprotobufRpcMethodInfo (com.baidu.brpc.JprotobufRpcMethodInfo)1 ProtobufRpcMethodInfo (com.baidu.brpc.ProtobufRpcMethodInfo)1 RpcMethodInfo (com.baidu.brpc.RpcMethodInfo)1