Netty游戏服务器实战开发(4):自定义消息池化处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_23086307/article/details/81636217

通过上篇《Netty游戏服务器实战开发(3):自定义消息》我们都知道,客户端发送过来的消息我们服务器通过自定义编解码实现解析每条消息,并且做对应的处理,但是当批量消息到达的时候我们不能做出及时处理,需要将消息放到队列中,然后在进行处理,提高系统的性能。但是上篇介绍的重点是消息的编解码,接下来我们介绍消息的处理,并且利用线程池化技术实现消息队列处理。

首先我们来复习一下java提供的几种队列模型。

BlockingQueue接口
提供了3个添加元素方法。

add:添加元素到队列里,添加成功返回true,由于容量满了添加失败会抛出IllegalStateException异常
offer:添加元素到队列里,添加成功返回true,添加失败返回false
put:添加元素到队列里,如果容量满了会阻塞直到容量不满

3个删除方法。
poll:删除队列头部元素,如果队列为空,返回null。否则返回元素。
remove:基于对象找到对应的元素,并删除。删除成功返回true,否则返回false
take:删除队列头部元素,如果队列为空,一直阻塞到队列有元素并删除
常用的阻塞队列具体类有ArrayBlockingQueue、LinkedBlockingQueue、PriorityBlockingQueue、LinkedBlockingDeque等。

ArrayBlockingQueue
ArrayBlockingQueue的原理就是使用一个可重入锁和这个锁生成的两个条件对象进行并发控制(classic two-condition algorithm)。

ArrayBlockingQueue是一个带有长度的阻塞队列,初始化的时候必须要指定队列长度,且指定长度之后不允许进行修改。

LinkedBlockingQueue
LinkedBlockingQueue是一个使用链表完成队列操作的阻塞队列。链表是单向链表,而不是双向链表。
内部使用放锁和拿锁,这两个锁实现阻塞(“two lock queue” algorithm)。

当然关于这部分的知识还是有很多的,这儿就不详细的介绍了,我们来看利用java通过的安全队列如何使用到我们的系统中

首先我们来看消息处理部分。
我们知道,netty通过自定义编解码后消息传入到对应的handler中,对于Netty中,Channel,ChannelHandler,和ChannelPipeline之间的关系我们用一张图来描述,具体的细节问题还是要去看看Netty in Action中的对应章节。

这里写图片描述

下面就是我们实现的代码,我们抽象一个AbstractNettyNetMessageTcpServerHandler 类来处理一些功能的方法。

/**
 * @author EGLS0807 - [Created on 2018-07-24 21:07]
 * @company http://www.g2us.com/
 * @jdk java version "1.8.0_77"
 */
public abstract class AbstractNettyNetMessageTcpServerHandler extends ChannelInboundHandlerAdapter {
    Logger logger = LoggerUtils.getLogger(AbstractNettyNetMessageTcpServerHandler.class);
    private int lossContextNumber = 0;

    /**
     * channel 注册
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelRegistered();
        NettyTcpSession nettyTcpSession = (NettyTcpSession) SpringServiceManager.springLoadService.getNettyTcpSessionBuilder().buildSession(ctx.channel());
        boolean can = SpringServiceManager.springLoadService.getNetTcpSessionLoopUpService().addNettySession(nettyTcpSession);
        if (!can) {
            AbstractNettyNetMessage errorMessage = SpringServiceManager.springLoadService.getNettyTcpMessageFactory().createCommonErrorResponseMessage(-1, 10500);
            nettyTcpSession.write(errorMessage);
            nettyTcpSession.close();
            ctx.close();
            return;
        }
        addUpdateSession(nettyTcpSession);
    }

    public abstract void addUpdateSession(NettyTcpSession nettyTcpSession);

    /**
     * have error in project
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error(cause.getMessage(), cause);
        if (cause instanceof java.io.IOException) {
            logger.error(cause.getMessage());
            //return;
        }
        //  if(logger.isTraceEnabled()){
        logger.error(cause.getMessage(), cause);
        //   }
        //设置下线
        disconnect(ctx.channel());
        //销毁上下文
        ctx.close();

    }

    /**
     * 下线操作
     *
     * @param channel
     */
    public void disconnect(Channel channel) {
        long sessionId = channel.attr(NettyTcpSessionBuilder.sessionId).get();
        NettyTcpSession nettySession = (NettyTcpSession) SpringServiceManager.springLoadService.getNetTcpSessionLoopUpService().findNettySession(sessionId);
        if (nettySession == null) {
            logger.error("TCP NET SESSION NULL CHANNEL ID IS:" + channel.id().asLongText());
            return;
        }
        nettySession.close();
    }

    /**
     * disconnect; interrupt
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    /**
     * heart loop check
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        long sessionId = ctx.channel().attr(NettyTcpSessionBuilder.sessionId).get();
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            switch (event.state()) {
                case ALL_IDLE:
                    logger.info("SESSION ID =" + sessionId + " IS ALL IDLE");
                    break;
                case READER_IDLE:
                    logger.info("SESSION ID =" + sessionId + " IS READER IDLE");
                    lossContextNumber++;
                    logger.info(lossContextNumber);
                    break;
                case WRITER_IDLE:
                    logger.info("SESSION ID =" + sessionId + " IS READER IDLE");
                    break;
                default:
                    break;
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
        if (lossContextNumber > GlobalConstants.NettyNet.SESSION_HEART_CHECK_NUMBER) {
            NettyTcpSession nettyTcpSession = (NettyTcpSession) SpringServiceManager.springLoadService.getNetTcpSessionLoopUpService().findNettySession(sessionId);
            disconnect(ctx.channel());
            if (nettyTcpSession == null) {
                ctx.fireChannelUnregistered();
                return;
            }
            // remove session
            SpringServiceManager.springLoadService.getNetTcpSessionLoopUpService().removeNettySession(nettyTcpSession.getSessionId());
            ctx.fireChannelUnregistered();
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

上面的代码我们可以看到,客户端登录消息到来的时候,检查是否合法,然后将生成对应的自定义session和channel保存起来,以方便记录下一次消息到来的时候破案是否是合法消息,而AbstractNettyNetMessageTcpServerHandler是一个抽象类,主要是为了封装一些共同的方法,比如前面说的注册channel,保存session,报错下线等,心跳检测等公共操作。
对于他的实现类,NettyNetMessageTcpServerHandler,实现channelRead()方法。

/**
 * @author EGLS0807 - [Created on 2018-07-26 21:11]
 * @company http://www.g2us.com/
 * @jdk java version "1.8.0_77"
 */
public class NettyNetMessageTcpServerHandler extends AbstractNettyNetMessageTcpServerHandler {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        AbstractNettyNetMessage message = (AbstractNettyNetMessage) msg;
        INettyServerPipeLine nettyTcpServerPipeLine = SpringServiceManager.springLoadService.getNettyTcpServerPipeLine();
        nettyTcpServerPipeLine.dispatch(ctx.channel(), message);
    }

    @Override
    public void addUpdateSession(NettyTcpSession nettyTcpSession) {
    }
}

上面代码中首先获得一条消息管道,在将消息注入到管道中

 nettyTcpServerPipeLine.dispatch(ctx.channel(), message);

由INettyServerpilpline的实现类来实现管道中处理消息,

tcp管道实现类如下NettyTcpServerPipeLineImpl

/**
 * @author EGLS0807 - [Created on 2018-08-02 20:41]
 * @company http://www.g2us.com/
 * @jdk java version "1.8.0_77"
 */
@Service
public class NettyTcpServerPipeLineImpl implements INettyServerPipeLine {

private Logger logger=LoggerUtils.getLogger(NettyTcpServerPipeLineImpl.class);
    @Override
    public void dispatch(Channel channel, AbstractNettyNetMessage message) {
        int commId = message.getNettyNetMessageHead().getCmd();
        MessageRegistryFactory messageRegistryFactory = SpringServiceManager.springLoadService.getMessageRegistryFactory();
        MessageComm messageComm = messageRegistryFactory.getMessageComm(commId);
        if (message instanceof AbstractNettyNetProtoBufTcpMessage) {
            AbstractNettyNetProtoBufTcpMessage protoBufTcpMessage = (AbstractNettyNetProtoBufTcpMessage) message;
            INettyChannleOperationService netTcpSessionLoopUpService = SpringServiceManager.springLoadService.getNetTcpSessionLoopUpService();
            long sessionId = channel.attr(NettyTcpSessionBuilder.sessionId).get();
            NettyTcpSession nettySession = (NettyTcpSession) netTcpSessionLoopUpService.findNettySession(sessionId);
            if(nettySession==null){
                logger.error("NETTY SESSION IS NULL");
            }
            message.setAttribute(MessageAttributeEnum.DISPATCH_SESSION,nettySession);
            nettySession.addNettyNetMessage(message);
        }

    }

首先是根据消息的id找到具体消息的注解,通过工厂类获取消息对象,然后通过执行器找到对应的session对象,最后通过session把消息添加到session中,而session中的addNettyNetMessage方法则是将消息添加到消息队列中去。由此,我们就可以从netty的handler模块将消息放到消息队列模块了。下面是消息session的具体逻辑。

/**
 * @author twjitm - [Created on 2018-07-24 15:59]
 * @jdk java version "1.8.0_77"
 * tcp session
 */
public class NettyTcpSession extends NettySession implements IUpdatable {
    /**
     * session id
     */
    private long sessionId;
    /**
     * 消息处理器
     */
    private NettyTcpNetProtoMessageProcess netProtoMessageProcess;
    /**
     * 消息发送器
     */
    private NettyNetTcpMessageSender netTcpMessageSender;

    boolean netMessageProcessSwitch = true;


    public NettyTcpSession(Channel channel) {
        super(channel);
        sessionId = SpringServiceManager.springLoadService.getLongIdGenerator().generateId();
        netProtoMessageProcess = new NettyTcpNetProtoMessageProcess(this);
        netTcpMessageSender = new NettyNetTcpMessageSender(this);


    }

    /**
     * @param switchFlag
     */
    public void processNetMessage(boolean switchFlag) {
        if (netMessageProcessSwitch || switchFlag) {
            netProtoMessageProcess.update();
        }
    }

    /**
     * @param abstractNetMessage
     */
    public void addNettyNetMessage(AbstractNettyNetMessage abstractNetMessage) {
        this.netProtoMessageProcess.addNetMessage(abstractNetMessage);
        this.processNetMessage(true);
    }

    public void close() {
        this.netProtoMessageProcess.close();
        this.netTcpMessageSender.close();
    }

    @Override
    public boolean update() {
        processNetMessage(false);
        return false;
    }

    public long getSessionId() {
        return sessionId;
    }

    public NettyTcpNetProtoMessageProcess getNetProtoMessageProcess() {
        return netProtoMessageProcess;
    }

    public NettyNetTcpMessageSender getNetTcpMessageSender() {
        return netTcpMessageSender;
    }

    public boolean isNetMessageProcessSwitch() {
        return netMessageProcessSwitch;
    }

最后将主要流程图用下图表示

这里写图片描述

猜你喜欢

转载自blog.csdn.net/baidu_23086307/article/details/81636217