编解码和数据包都解决了,下面来关注一下,业务处理方面的功能怎样进行设计。
1. 构建 NettyServerHandler 类,完成业务逻辑的处理功能。
A. 我们需要一个自定义的线程池,用来执行业务逻辑的处理代码;
B. 我们需要封装一下业务处理环节,服务端的业务处理模式比较简单,基本上采用一个请求对应一个应答的操作,所以,可以提取出统一的调用接口 ServerAction 进行业务处理,之后针对不同的请求设计对应的实现类即可。业务处理环节除了 ServerAction 以外,还需要 请求包的类型 和 应答包的类型 信息。
C. 构建一个映射关系,Key是请求包的类型,Value是对应的业务处理环节。我们可以通过映射关系快速定位业务处理的 ServerAction 实现类的对象,以及,应答包JavaBean的实例化。
2. 与SpringBoot的集成
A. 配置参数的自动装配
B. 映射关系的自动注册
package houlei.net.tcp.hdr;
import io.netty.channel.ChannelHandlerContext;
@FunctionalInterface
public interface ServerAction<REQ, RSP> {
void execute(ChannelHandlerContext ctx, REQ request, RSP response);
}
package houlei.net.tcp.hdr;
import houlei.net.tcp.pkg.PackageFactory;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;