did/did-server/src/main/java/io/github/ehlxr/did/server/sdk/SdkServerHandler.java

62 lines
2.3 KiB
Java
Raw Normal View History

2021-01-22 07:40:02 +00:00
package io.github.ehlxr.did.server.sdk;
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;
import io.github.ehlxr.did.core.SnowFlake;
2021-01-19 06:45:49 +00:00
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
2018-08-14 07:21:56 +00:00
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* ID Channel
*
* @author ehlxr
*/
2021-01-18 08:17:14 +00:00
public class SdkServerHandler extends SimpleChannelInboundHandler<SdkProto> {
2018-08-14 07:21:56 +00:00
private static final Logger logger = LoggerFactory.getLogger(SdkServerHandler.class);
/**
*
*/
2021-01-20 07:25:58 +00:00
private final Semaphore semaphore = new Semaphore(Constants.HANDLE_SDK_TPS);
2021-01-18 08:17:14 +00:00
private final SnowFlake snowFlake;
2018-08-14 07:21:56 +00:00
SdkServerHandler(SnowFlake snowFlake) {
this.snowFlake = snowFlake;
}
@Override
2021-01-18 08:17:14 +00:00
protected void channelRead0(ChannelHandlerContext ctx, SdkProto sdkProto) throws Exception {
if (semaphore.tryAcquire(Constants.ACQUIRE_TIMEOUTMILLIS, TimeUnit.MILLISECONDS)) {
try {
sdkProto.setDid(snowFlake.nextId());
2021-01-19 10:39:42 +00:00
2021-01-19 06:45:49 +00:00
ctx.channel().writeAndFlush(sdkProto).addListener((ChannelFutureListener) channelFuture -> semaphore.release());
2021-01-18 08:17:14 +00:00
} catch (Exception e) {
semaphore.release();
logger.error("SdkServerhandler error", e);
2018-08-14 07:21:56 +00:00
}
2021-01-18 08:17:14 +00:00
} else {
sdkProto.setDid(-1);
ctx.channel().writeAndFlush(sdkProto);
String info = String.format("SdkServerHandler tryAcquire semaphore timeout, %dms, waiting thread " + "nums: %d availablePermit: %d",
Constants.ACQUIRE_TIMEOUTMILLIS, this.semaphore.getQueueLength(), this.semaphore.availablePermits());
logger.warn(info);
throw new Exception(info);
2018-08-14 07:21:56 +00:00
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
Channel channel = ctx.channel();
logger.error("SdkServerHandler channel [{}] error and will be closed", NettyUtil.parseRemoteAddr(channel), cause);
NettyUtil.closeChannel(channel);
}
}