did/did-sdk/src/main/java/io/github/ehlxr/did/client/AbstractClient.java

174 lines
6.7 KiB
Java
Raw Normal View History

2021-01-22 07:40:02 +00:00
package io.github.ehlxr.did.client;
2018-08-14 07:21:56 +00:00
2021-01-22 07:40:02 +00:00
import io.github.ehlxr.did.common.Constants;
import io.github.ehlxr.did.common.NettyUtil;
import io.github.ehlxr.did.common.SdkProto;
2018-08-14 07:21:56 +00:00
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.nio.NioEventLoopGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
2021-01-20 07:25:58 +00:00
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
2018-08-14 07:21:56 +00:00
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author ehlxr
*/
2021-01-20 07:25:58 +00:00
@SuppressWarnings({"unused", "UnusedReturnValue"})
2018-08-14 07:21:56 +00:00
public abstract class AbstractClient implements Client {
2021-01-19 06:45:49 +00:00
private final Logger logger = LoggerFactory.getLogger(AbstractClient.class);
2018-08-14 07:21:56 +00:00
2021-01-20 07:25:58 +00:00
private final Semaphore asyncSemaphore = new Semaphore(Constants.SDK_CLIENT_ASYNC_TPS);
private final Semaphore onewaySemaphore = new Semaphore(Constants.SDK_CLIENT_ONEWAY_TPS);
2018-08-14 07:21:56 +00:00
NioEventLoopGroup workGroup;
ChannelFuture channelFuture;
Bootstrap bootstrap;
2021-01-20 07:25:58 +00:00
int timeoutMillis;
String host;
int port;
2021-01-19 10:39:42 +00:00
public void setTimeoutMillis(int timeoutMillis) {
this.timeoutMillis = timeoutMillis;
}
2021-01-20 07:25:58 +00:00
public void setHost(String host) {
this.host = host;
}
public void setPort(int port) {
this.port = port;
}
void init() {
workGroup = new NioEventLoopGroup(new ThreadFactory() {
2021-01-19 06:45:49 +00:00
private final AtomicInteger index = new AtomicInteger(0);
2018-08-14 07:21:56 +00:00
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "WORK_" + index.incrementAndGet());
}
});
bootstrap = new Bootstrap();
}
@Override
public void shutdown() {
2021-01-20 07:25:58 +00:00
logger.info("SDK Client shutdowning......");
try {
if (workGroup != null) {
workGroup.shutdownGracefully().sync();
}
} catch (Exception e) {
logger.error("Client EventLoopGroup shutdown error.", e);
2018-08-14 07:21:56 +00:00
}
2021-01-20 07:25:58 +00:00
logger.info("SDK Client shutdown finish!");
}
2018-08-14 07:21:56 +00:00
@Override
2021-01-20 07:25:58 +00:00
public SdkProto invokeSync(long timeoutMillis) throws Exception {
2018-08-14 07:21:56 +00:00
final Channel channel = channelFuture.channel();
if (channel.isActive()) {
2021-01-20 07:25:58 +00:00
final SdkProto sdkProto = new SdkProto();
2018-08-14 07:21:56 +00:00
final int rqid = sdkProto.getRqid();
try {
2021-01-20 07:25:58 +00:00
final ResponseFuture responseFuture = new ResponseFuture(timeoutMillis, null, null);
REPONSE_MAP.put(rqid, responseFuture);
2021-01-19 06:45:49 +00:00
channel.writeAndFlush(sdkProto).addListener((ChannelFutureListener) channelFuture -> {
if (channelFuture.isSuccess()) {
//发送成功后立即跳出
return;
2018-08-14 07:21:56 +00:00
}
2021-01-19 06:45:49 +00:00
// 代码执行到此说明发送失败,需要释放资源
2021-01-20 07:25:58 +00:00
REPONSE_MAP.remove(rqid);
2021-01-19 06:45:49 +00:00
responseFuture.putResponse(null);
responseFuture.setCause(channelFuture.cause());
2021-01-20 07:25:58 +00:00
logger.warn("send a request command to channel <{}> failed.", NettyUtil.parseRemoteAddr(channel));
2018-08-14 07:21:56 +00:00
});
// 阻塞等待响应
SdkProto resultProto = responseFuture.waitResponse(timeoutMillis);
if (null == resultProto) {
2021-01-20 07:25:58 +00:00
throw new Exception(NettyUtil.parseRemoteAddr(channel), responseFuture.getCause());
2018-08-14 07:21:56 +00:00
}
return resultProto;
} catch (Exception e) {
logger.error("invokeSync fail, addr is " + NettyUtil.parseRemoteAddr(channel), e);
throw new Exception(NettyUtil.parseRemoteAddr(channel), e);
} finally {
2021-01-20 07:25:58 +00:00
REPONSE_MAP.remove(rqid);
2018-08-14 07:21:56 +00:00
}
} else {
NettyUtil.closeChannel(channel);
throw new Exception(NettyUtil.parseRemoteAddr(channel));
}
}
@Override
2021-01-20 07:25:58 +00:00
public void invokeAsync(long timeoutMillis, InvokeCallback invokeCallback) throws Exception {
2018-08-14 07:21:56 +00:00
final Channel channel = channelFuture.channel();
if (channel.isOpen() && channel.isActive()) {
2021-01-20 07:25:58 +00:00
final SdkProto sdkProto = new SdkProto();
2018-08-14 07:21:56 +00:00
final int rqid = sdkProto.getRqid();
2021-01-20 07:25:58 +00:00
if (asyncSemaphore.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS)) {
final ResponseFuture responseFuture = new ResponseFuture(timeoutMillis, invokeCallback, asyncSemaphore);
REPONSE_MAP.put(rqid, responseFuture);
2018-08-14 07:21:56 +00:00
try {
2021-01-20 07:25:58 +00:00
channelFuture.channel().writeAndFlush(sdkProto).addListener(channelFuture -> {
2021-01-19 06:45:49 +00:00
if (channelFuture.isSuccess()) {
return;
}
// 代码执行到些说明发送失败,需要释放资源
2021-01-20 07:25:58 +00:00
REPONSE_MAP.remove(rqid);
2021-01-19 06:45:49 +00:00
responseFuture.setCause(channelFuture.cause());
responseFuture.putResponse(null);
2018-08-14 07:21:56 +00:00
2021-01-19 06:45:49 +00:00
try {
responseFuture.executeInvokeCallback();
} catch (Exception e) {
logger.warn("excute callback in writeAndFlush addListener, and callback throw", e);
} finally {
responseFuture.release();
2018-08-14 07:21:56 +00:00
}
2021-01-20 07:25:58 +00:00
logger.warn("send a request command to channel <{}> failed.",
NettyUtil.parseRemoteAddr(channel), channelFuture.cause());
2018-08-14 07:21:56 +00:00
});
} catch (Exception e) {
responseFuture.release();
2021-01-20 07:25:58 +00:00
logger.warn("send a request to channel <{}> Exception",
NettyUtil.parseRemoteAddr(channel), e);
2018-08-14 07:21:56 +00:00
throw new Exception(NettyUtil.parseRemoteAddr(channel), e);
}
} else {
2021-01-20 07:25:58 +00:00
String info = String.format("invokeAsyncImpl tryAcquire semaphore timeout, %dms, waiting thread " +
"nums: %d semaphoreAsyncValue: %d",
2021-01-19 06:45:49 +00:00
timeoutMillis, this.asyncSemaphore.getQueueLength(), this.asyncSemaphore.availablePermits());
2018-08-14 07:21:56 +00:00
logger.warn(info);
throw new Exception(info);
}
} else {
NettyUtil.closeChannel(channel);
throw new Exception(NettyUtil.parseRemoteAddr(channel));
}
}
2021-01-19 10:39:42 +00:00
public long invoke() throws Exception {
return invoke(timeoutMillis);
}
2021-01-20 07:25:58 +00:00
public SdkProto invokeSync() throws Exception {
return invokeSync(timeoutMillis);
}
public void invokeAsync(InvokeCallback invokeCallback) throws Exception {
invokeAsync(timeoutMillis, invokeCallback);
}
2018-08-14 07:21:56 +00:00
}