com.turbospaces.grpc.AbstractGrpcServiceApi Maven / Gradle / Ivy
package com.turbospaces.grpc;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.DisposableBean;
import com.turbospaces.boot.AbstractBootstrapAware;
import com.turbospaces.boot.Bootstrap;
import com.turbospaces.ups.PlainServiceInfo;
import io.grpc.Channel;
import io.grpc.ClientInterceptors;
import io.grpc.ManagedChannel;
import io.grpc.netty.GrpcUtil;
import io.grpc.netty.NettyChannelBuilder;
import io.netty.channel.ChannelOption;
public abstract class AbstractGrpcServiceApi extends AbstractBootstrapAware implements DisposableBean {
private ManagedChannel managedChannel;
protected NettyChannelBuilder builder;
protected Channel channel;
protected AbstractGrpcServiceApi(PlainServiceInfo si) {
this.builder = null;
switch (si.getScheme()) {
case PlainServiceInfo.DNS_SCHEME: {
this.builder = NettyChannelBuilder.forTarget(si.getUri());
break;
}
case PlainServiceInfo.HTTP_SCHEME:
case PlainServiceInfo.HTTPS_SCHEME: {
this.builder = NettyChannelBuilder.forAddress(si.getHost(), si.getPort());
break;
}
default: {
throw new IllegalArgumentException("Unexpected value: " + si.getScheme());
}
}
this.builder = builder.usePlaintext().directExecutor();
}
protected AbstractGrpcServiceApi(NettyChannelBuilder builder) {
this.builder = builder.usePlaintext().directExecutor();
}
@Override
public void setBootstrap(Bootstrap bootstrap) throws Throwable {
super.setBootstrap(bootstrap);
var clientInterceptor = new GrpcClientInterceptor();
clientInterceptor.setBootstrap(bootstrap);
managedChannel = configureManagedChannel().build();
managedChannel.getState(true);
channel = ClientInterceptors.intercept(managedChannel, clientInterceptor);
logger.info("epoll available: {}", GrpcUtil.isEpollAvailable());
}
@Override
public void destroy() throws Exception {
if (Objects.nonNull(managedChannel)) {
managedChannel.shutdown();
}
}
protected NettyChannelBuilder configureManagedChannel() {
var props = bootstrap.props();
var connectTimeout = props.TCP_CONNECTION_TIMEOUT.get();
var keepAlive = props.TCP_KEEP_ALIVE.get();
var noDelay = props.TCP_NO_DELAY.get();
var keepAliveTimeout = props.TCP_KEEP_ALIVE_TIMEOUT.get();
builder.enableRetry();
builder.defaultLoadBalancingPolicy("round_robin");
builder.withOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout.toMillis());
builder.withOption(ChannelOption.SO_KEEPALIVE, keepAlive);
builder.withOption(ChannelOption.TCP_NODELAY, noDelay);
if (keepAlive) {
builder.keepAliveWithoutCalls(keepAlive);
builder.keepAliveTime(1, TimeUnit.SECONDS);
builder.keepAliveTimeout(keepAliveTimeout.toMillis(), TimeUnit.MILLISECONDS);
}
return builder;
}
}