Java Code Examples for io.grpc.netty.NettyChannelBuilder#keepAliveTimeout()

The following examples show how to use io.grpc.netty.NettyChannelBuilder#keepAliveTimeout() . 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: DefaultChannelFactory.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private void setupClientOption(final NettyChannelBuilder channelBuilder) {
    channelBuilder.keepAliveTime(clientOption.getKeepAliveTime(), TimeUnit.MILLISECONDS);
    channelBuilder.keepAliveTimeout(clientOption.getKeepAliveTimeout(), TimeUnit.MILLISECONDS);
    channelBuilder.keepAliveWithoutCalls(clientOption.isKeepAliveWithoutCalls());
    channelBuilder.maxHeaderListSize(clientOption.getMaxHeaderListSize());
    channelBuilder.maxInboundMessageSize(clientOption.getMaxInboundMessageSize());
    channelBuilder.flowControlWindow(clientOption.getFlowControlWindow());
    channelBuilder.idleTimeout(clientOption.getIdleTimeoutMillis(), TimeUnit.MILLISECONDS);

    // ChannelOption
    channelBuilder.withOption(ChannelOption.TCP_NODELAY, true);
    channelBuilder.withOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, clientOption.getConnectTimeout());

    final WriteBufferWaterMark writeBufferWaterMark = new WriteBufferWaterMark(clientOption.getWriteBufferLowWaterMark(), clientOption.getWriteBufferHighWaterMark());
    channelBuilder.withOption(ChannelOption.WRITE_BUFFER_WATER_MARK, writeBufferWaterMark);
    if (logger.isInfoEnabled()) {
        logger.info("Set clientOption {}. name={}", clientOption, factoryName);
    }
}
 
Example 2
Source File: EtcdClient.java    From etcd-java with Apache License 2.0 4 votes vote down vote up
EtcdClient(NettyChannelBuilder chanBuilder, long defaultTimeoutMs,
            ByteString name, ByteString password, boolean initialAuth,
            int threads, Executor userExecutor, boolean sendViaEventLoop,
            int sessTimeoutSecs) {

        if (name == null && password != null) {
            throw new IllegalArgumentException("password without name");
        }
        this.name = name;
        this.password = password;
        this.sessionTimeoutSecs = sessTimeoutSecs;

        chanBuilder.keepAliveTime(10L, SECONDS);
        chanBuilder.keepAliveTimeout(8L, SECONDS);

        int connTimeout = Math.min((int) defaultTimeoutMs, 6000);
        chanBuilder.withOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, connTimeout);

        //TODO loadbalancer TBD
//      chanBuilder.loadBalancerFactory(RoundRobinLoadBalancerFactory.getInstance());

        ThreadFactory tfac = new ThreadFactoryBuilder().setDaemon(true)
                .setThreadFactory(EtcdEventThread::new)
                .setNameFormat("etcd-event-pool-%d").build();

        Class<? extends Channel> channelType;
        if (Epoll.isAvailable()) {
            this.internalExecutor = new EpollEventLoopGroup(threads, tfac);
            channelType = EpollSocketChannel.class;
        } else {
            this.internalExecutor = new NioEventLoopGroup(threads, tfac);
            channelType = NioSocketChannel.class;
        }

        chanBuilder.eventLoopGroup(internalExecutor).channelType(channelType);

        if (userExecutor == null) {
            //TODO default chan executor TBD
            userExecutor = Executors.newCachedThreadPool(
                    new ThreadFactoryBuilder().setDaemon(true)
                    .setNameFormat("etcd-callback-thread-%d").build());
        }
        chanBuilder.executor(userExecutor);

        this.channel = chanBuilder.build();

        AuthProvider authProvider = name == null ? null : new AuthProvider() {
            @Override
            public boolean requiresReauth(Throwable t) {
                return EtcdClient.reauthRequired(t);
            }
            @Override
            public CallCredentials refreshCredentials(Throwable trigger) {
                return EtcdClient.this.refreshCredentials(trigger);
            }
            @Override
            public CallCredentials refreshCredentials() {
                return refreshCredentials(null);
            }
        };

        this.sharedInternalExecutor = new SharedScheduledExecutorService(internalExecutor);
        this.grpc = new GrpcClient(channel, authProvider, sharedInternalExecutor,
                () -> Thread.currentThread() instanceof EtcdEventThread,
                userExecutor, sendViaEventLoop, defaultTimeoutMs);
        if (authProvider != null && initialAuth) {
            grpc.authenticateNow();
        }

        this.kvClient = new EtcdKvClient(grpc);
    }
 
Example 3
Source File: Channels.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public static Channel createChannel(String name) throws SSLException {
    InstanceHandle<GrpcClientConfigProvider> instance = Arc.container().instance(GrpcClientConfigProvider.class);

    if (!instance.isAvailable()) {
        throw new IllegalStateException("Unable to find the GrpcClientConfigProvider");
    }

    GrpcClientConfiguration config = instance.get().getConfiguration(name);
    String host = config.host;
    int port = config.port;
    boolean plainText = !config.ssl.trustStore.isPresent();
    Optional<Boolean> usePlainText = config.plainText;
    if (usePlainText.isPresent()) {
        plainText = usePlainText.get();
    }

    SslContext context = null;
    if (!plainText) {
        Path trustStorePath = config.ssl.trustStore.orElse(null);
        Path certificatePath = config.ssl.certificate.orElse(null);
        Path keyPath = config.ssl.key.orElse(null);
        SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();
        if (trustStorePath != null) {
            sslContextBuilder.trustManager(trustStorePath.toFile());
        }

        if (certificatePath != null && keyPath != null) {
            sslContextBuilder.keyManager(certificatePath.toFile(), keyPath.toFile());
        }

        context = sslContextBuilder.build();
    }

    NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port)
            .flowControlWindow(config.flowControlWindow.orElse(DEFAULT_FLOW_CONTROL_WINDOW))
            .keepAliveWithoutCalls(config.keepAliveWithoutCalls)
            .maxHedgedAttempts(config.maxHedgedAttempts)
            .maxRetryAttempts(config.maxRetryAttempts)
            .maxInboundMetadataSize(config.maxInboundMessageSize.orElse(DEFAULT_MAX_HEADER_LIST_SIZE))
            .maxInboundMetadataSize(config.maxInboundMessageSize.orElse(DEFAULT_MAX_MESSAGE_SIZE))
            .negotiationType(NegotiationType.valueOf(config.negotiationType.toUpperCase()));

    if (config.retry) {
        builder.enableRetry();
    } else {
        builder.disableRetry();
    }

    if (config.maxTraceEvents.isPresent()) {
        builder.maxTraceEvents(config.maxTraceEvents.getAsInt());
    }
    Optional<String> userAgent = config.userAgent;
    if (userAgent.isPresent()) {
        builder.userAgent(userAgent.get());
    }
    if (config.retryBufferSize.isPresent()) {
        builder.retryBufferSize(config.retryBufferSize.getAsLong());
    }
    if (config.perRpcBufferLimit.isPresent()) {
        builder.perRpcBufferLimit(config.perRpcBufferLimit.getAsLong());
    }
    Optional<String> overrideAuthority = config.overrideAuthority;
    if (overrideAuthority.isPresent()) {
        builder.overrideAuthority(overrideAuthority.get());
    }
    Optional<Duration> keepAliveTime = config.keepAliveTime;
    if (keepAliveTime.isPresent()) {
        builder.keepAliveTime(keepAliveTime.get().toMillis(), TimeUnit.MILLISECONDS);
    }
    Optional<Duration> keepAliveTimeout = config.keepAliveTimeout;
    if (keepAliveTimeout.isPresent()) {
        builder.keepAliveTimeout(keepAliveTimeout.get().toMillis(), TimeUnit.MILLISECONDS);
    }
    Optional<Duration> idleTimeout = config.idleTimeout;
    if (idleTimeout.isPresent()) {
        builder.keepAliveTimeout(idleTimeout.get().toMillis(), TimeUnit.MILLISECONDS);
    }

    if (plainText) {
        builder.usePlaintext();
    }
    if (context != null) {
        builder.sslContext(context);
    }

    // Client-side interceptors
    Instance<ClientInterceptor> interceptors = Arc.container().beanManager().createInstance()
            .select(ClientInterceptor.class);
    for (ClientInterceptor clientInterceptor : getSortedInterceptors(interceptors)) {
        builder.intercept(clientInterceptor);
    }

    return builder.build();
}