use java8 functional

This commit is contained in:
2021-02-08 17:15:36 +08:00
parent e929cd180f
commit 169bf6f290
20 changed files with 536 additions and 149 deletions

View File

@@ -1,5 +1,6 @@
package io.github.ehlxr.did.server;
import io.github.ehlxr.did.common.Try;
import io.github.ehlxr.did.core.SnowFlake;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
@@ -52,9 +53,8 @@ public abstract class BaseServer implements Server {
}
});
serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workGroup)
serverBootstrap = new ServerBootstrap()
.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
// .option(ChannelOption.SO_KEEPALIVE, true)
// .option(ChannelOption.TCP_NODELAY, true)
@@ -64,15 +64,13 @@ public abstract class BaseServer implements Server {
@Override
public void shutdown() {
try {
Try.of(() -> {
// 同步阻塞 shutdownGracefully 完成
if (defLoopGroup != null) {
defLoopGroup.shutdownGracefully().sync();
}
bossGroup.shutdownGracefully().sync();
workGroup.shutdownGracefully().sync();
} catch (Exception e) {
logger.error("Server EventLoopGroup shutdown error.", e);
}
}).trap(e -> logger.error("Server EventLoopGroup shutdown error.", e)).run();
}
}

View File

@@ -1,6 +1,7 @@
package io.github.ehlxr.did.server.http;
import io.github.ehlxr.did.common.Constants;
import io.github.ehlxr.did.common.Try;
import io.github.ehlxr.did.core.SnowFlake;
import io.github.ehlxr.did.server.BaseServer;
import io.netty.channel.ChannelInitializer;
@@ -46,7 +47,7 @@ public class HttpServer extends BaseServer {
@Override
public void start() {
try {
Try.of(() -> {
init();
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@@ -63,9 +64,7 @@ public class HttpServer extends BaseServer {
channelFuture = serverBootstrap.bind(port).sync();
logger.info("HttpServer start success, port is:{}", port);
} catch (InterruptedException e) {
logger.error("HttpServer start fail,", e);
}
}).trap(e -> logger.error("HttpServer start fail,", e)).run();
}
public static final class HttpServerBuilder {

View File

@@ -33,6 +33,8 @@ public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpReque
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
logger.debug("http server handler receive request {}", request);
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
Result<?> result;
@@ -48,23 +50,14 @@ public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpReque
}
if (semaphore.tryAcquire(Constants.ACQUIRE_TIMEOUTMILLIS, TimeUnit.MILLISECONDS)) {
try {
long id = snowFlake.nextId();
logger.info("HttpServerHandler id is: {}", id);
long id = snowFlake.nextId();
status = HttpResponseStatus.OK;
result = Result.success(SdkProto.newBuilder().did(id).build());
} catch (Exception e) {
semaphore.release();
logger.error("HttpServerHandler error", e);
status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
result = Result.fail(status.code(), status.reasonPhrase());
}
status = HttpResponseStatus.OK;
result = Result.success(SdkProto.newBuilder().did(id).build());
} else {
String info = String.format("HttpServerHandler tryAcquire semaphore timeout, %dms, waiting thread " + "nums: %d availablePermit: %d",
Constants.ACQUIRE_TIMEOUTMILLIS, this.semaphore.getQueueLength(), this.semaphore.availablePermits());
logger.warn(info);
logger.error(info);
status = HttpResponseStatus.SERVICE_UNAVAILABLE;
result = Result.fail(status.code(), info);
@@ -73,6 +66,7 @@ public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpReque
response.setStatus(status)
.content().writeBytes(result.toString().getBytes());
logger.debug("http server handler write response {} restul {} to channel", status, result);
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

View File

@@ -1,6 +1,7 @@
package io.github.ehlxr.did.server.sdk;
import io.github.ehlxr.did.common.Constants;
import io.github.ehlxr.did.common.Try;
import io.github.ehlxr.did.core.SnowFlake;
import io.github.ehlxr.did.server.BaseServer;
import io.netty.channel.ChannelInitializer;
@@ -41,14 +42,15 @@ public class SdkServer extends BaseServer {
@Override
public void start() {
try {
Try.of(() -> {
init();
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(defLoopGroup,
new SdkServerDecoder(12),
new SdkServerDecoder(),
// new SdkServerDecoder(12),
new SdkServerEncoder(),
new SdkServerHandler(snowFlake)
);
@@ -57,9 +59,7 @@ public class SdkServer extends BaseServer {
channelFuture = serverBootstrap.bind(port).sync();
logger.info("SdkServer start success, port is:{}", port);
} catch (InterruptedException e) {
logger.error("SdkServer start fail,", e);
}
}).trap(e -> logger.error("SdkServer start fail,", e)).run();
}
public static final class SdkServerBuilder {

View File

@@ -1,42 +1,30 @@
package io.github.ehlxr.did.server.sdk;
import io.github.ehlxr.did.common.NettyUtil;
import io.github.ehlxr.did.common.SdkProto;
import io.github.ehlxr.did.common.Try;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* @author ehlxr
*/
public class SdkServerDecoder extends FixedLengthFrameDecoder {
private static final Logger logger = LoggerFactory.getLogger(SdkServerDecoder.class);
SdkServerDecoder(int frameLength) {
super(frameLength);
}
public class SdkServerDecoder extends ByteToMessageDecoder {
private final Logger logger = LoggerFactory.getLogger(SdkServerDecoder.class);
@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) {
ByteBuf buf = null;
try {
buf = (ByteBuf) super.decode(ctx, in);
if (buf == null) {
return null;
}
return new SdkProto(buf.readInt(), buf.readLong());
} catch (Exception e) {
logger.error("decode exception, " + NettyUtil.parseRemoteAddr(ctx.channel()), e);
NettyUtil.closeChannel(ctx.channel());
} finally {
if (buf != null) {
buf.release();
}
}
return null;
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
Try.of(() -> {
byte[] bytes = new byte[in.readableBytes()];
in.readBytes(bytes);
out.add(NettyUtil.toObject(bytes));
}).trap(e -> logger.error("decode error", e)).run();
}
@Override
@@ -45,4 +33,4 @@ public class SdkServerDecoder extends FixedLengthFrameDecoder {
logger.error("SdkServerDecoder channel [{}] error and will be closed", NettyUtil.parseRemoteAddr(channel), cause);
NettyUtil.closeChannel(channel);
}
}
}

View File

@@ -2,6 +2,7 @@ package io.github.ehlxr.did.server.sdk;
import io.github.ehlxr.did.common.NettyUtil;
import io.github.ehlxr.did.common.SdkProto;
import io.github.ehlxr.did.common.Try;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
@@ -15,11 +16,11 @@ import org.slf4j.LoggerFactory;
public class SdkServerEncoder extends MessageToByteEncoder<SdkProto> {
private static final Logger logger = LoggerFactory.getLogger(SdkServerEncoder.class);
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, SdkProto sdkProto, ByteBuf out) {
out.writeInt(sdkProto.getRqid());
out.writeLong(sdkProto.getDid());
Try.of(() -> {
out.writeBytes(NettyUtil.toBytes(sdkProto));
}).trap(e -> logger.error("encode error", e)).run();
}
@Override

View File

@@ -33,6 +33,8 @@ public class SdkServerHandler extends SimpleChannelInboundHandler<SdkProto> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, SdkProto sdkProto) throws Exception {
logger.debug("sdk server handler receive sdkProto {}", sdkProto);
if (semaphore.tryAcquire(Constants.ACQUIRE_TIMEOUTMILLIS, TimeUnit.MILLISECONDS)) {
sdkProto.setDid(snowFlake.nextId());
@@ -42,6 +44,7 @@ public class SdkServerHandler extends SimpleChannelInboundHandler<SdkProto> {
Constants.ACQUIRE_TIMEOUTMILLIS, this.semaphore.getQueueLength(), this.semaphore.availablePermits());
}
logger.debug("sdk server handler write sdkProto {} to channel", sdkProto);
ctx.channel().
writeAndFlush(sdkProto).
addListener(ChannelFutureListener.CLOSE_ON_FAILURE);

View File

@@ -36,10 +36,12 @@
</encoder>
</appender>
<root level="INFO">
<root level="DEBUUG">
<appender-ref ref="STDOUT"/>
<appender-ref ref="ERROR"/>
<appender-ref ref="NORMAL"/>
</root>
<logger name="io.netty" level="OFF"/>
</configuration>