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

57 lines
2.0 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)) {
2021-02-07 10:21:08 +00:00
sdkProto.setDid(snowFlake.nextId());
semaphore.release();
2021-01-18 08:17:14 +00:00
} else {
2021-02-07 14:11:59 +00:00
logger.error("tryAcquire timeout after {}ms, {} threads waiting to acquire, {} permits available in this semaphore",
2021-01-18 08:17:14 +00:00
Constants.ACQUIRE_TIMEOUTMILLIS, this.semaphore.getQueueLength(), this.semaphore.availablePermits());
2018-08-14 07:21:56 +00:00
}
2021-02-07 10:21:08 +00:00
ctx.channel().
writeAndFlush(sdkProto).
addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
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);
}
}