Apache mina 源码再读3 I/O Service 源码剖析

2024-02-18 06:58

本文主要是介绍Apache mina 源码再读3 I/O Service 源码剖析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


Base interface for all  IoAcceptor  and  IoConnector  that provide I/O service and manage   IoSession.

public interface IoService { }


IoAcceptor 和IoConnector  的基础接口IoService 来提供I/O服务和管理IoSession .




public interface IoService {


/**
     * Adds an {@link IoServiceListener} that listens any events related with
     * this service.
     */
    void addListener(IoServiceListener listener);


    /**
     * Removed an existing {@link IoServiceListener} that listens any events
     * related with this service.
     */
    void removeListener(IoServiceListener listener);


 /**
     * Returns the handler which will handle all connections managed by this service.
     */
    IoHandler getHandler();


    /**
     * Sets the handler which will handle all connections managed by this service.
     */
    void setHandler(IoHandler handler);


    /**
     * Returns the map of all sessions which are currently managed by this
     * service.  The key of map is the {@link IoSession#getId() ID} of the
     * session.
     *
     * @return the sessions. An empty collection if there's no session.
     */
    Map<Long, IoSession> getManagedSessions();


    /**
     * Returns the number of all sessions which are currently managed by this
     * service.
     */
    int getManagedSessionCount();


    /**
     * Returns the default configuration of the new {@link IoSession}s
     * created by this service.
     */
    IoSessionConfig getSessionConfig();


    /**
     * Returns the {@link IoFilterChainBuilder} which will build the
     * {@link IoFilterChain} of all {@link IoSession}s which is created
     * by this service.
     * The default value is an empty {@link DefaultIoFilterChainBuilder}.
     */
    IoFilterChainBuilder getFilterChainBuilder();


    /**
     * Sets the {@link IoFilterChainBuilder} which will build the
     * {@link IoFilterChain} of all {@link IoSession}s which is created
     * by this service.
     * If you specify <tt>null</tt> this property will be set to
     * an empty {@link DefaultIoFilterChainBuilder}.
     */
    void setFilterChainBuilder(IoFilterChainBuilder builder);


    /**
     * A shortcut for <tt>( ( DefaultIoFilterChainBuilder ) </tt>{@link #getFilterChainBuilder()}<tt> )</tt>.
     * Please note that the returned object is not a <b>real</b> {@link IoFilterChain}
     * but a {@link DefaultIoFilterChainBuilder}.  Modifying the returned builder
     * won't affect the existing {@link IoSession}s at all, because
     * {@link IoFilterChainBuilder}s affect only newly created {@link IoSession}s.
     *
     * @throws IllegalStateException if the current {@link IoFilterChainBuilder} is
     *                               not a {@link DefaultIoFilterChainBuilder}
     */
    DefaultIoFilterChainBuilder getFilterChain();


    /**
     * Returns a value of whether or not this service is active
     *
     * @return whether of not the service is active.
     */
    boolean isActive();


    /**
     * Returns the time when this service was activated.  It returns the last
     * time when this service was activated if the service is not active now.
     *
     * @return The time by using {@link System#currentTimeMillis()}
     */
    long getActivationTime();


    /**
     * Writes the specified {@code message} to all the {@link IoSession}s
     * managed by this service.  This method is a convenience shortcut for
     * {@link IoUtil#broadcast(Object, Collection)}.
     */
    Set<WriteFuture> broadcast(Object message);


    /**
     * Returns the {@link IoSessionDataStructureFactory} that provides
     * related data structures for a new session created by this service.
     */
    IoSessionDataStructureFactory getSessionDataStructureFactory();


    /**
     * Sets the {@link IoSessionDataStructureFactory} that provides
     * related data structures for a new session created by this service.
     */
    void setSessionDataStructureFactory(IoSessionDataStructureFactory sessionDataStructureFactory);


    /**
     * Returns the number of bytes scheduled to be written
     *
     * @return The number of bytes scheduled to be written
     */
    int getScheduledWriteBytes();


    /**
     * Returns the number of messages scheduled to be written
     *
     * @return The number of messages scheduled to be written
     */
    int getScheduledWriteMessages();


    /**
     * Returns the IoServiceStatistics object for this service.
     * 
     * @return The statistics object for this service.
     */
    IoServiceStatistics getStatistics();


}


An instance of IoService contains an Executor which will handle the incoming  events

一个包含Executor 接口的IoService 抽象类,来处理incoming events.

public abstract class AbstractIoService implements IoService { }



public abstract class AbstractIoService implements IoService {

    /**
     * The unique number identifying the Service. It's incremented
     * for each new IoService created.
     */
    private static final AtomicInteger id = new AtomicInteger();


    /**
     * The thread name built from the IoService inherited
     * instance class name and the IoService Id
     **/
    private final String threadName;


    /**
     * The associated executor, responsible for handling execution of I/O events.
     */


    private final Executor executor;
    /**
     * A flag used to indicate that the local executor has been created
     * inside this instance, and not passed by a caller.
     * 
     * If the executor is locally created, then it will be an instance
     * of the ThreadPoolExecutor class.
     */
    private final boolean createdExecutor;


    /**
     * The IoHandler in charge of managing all the I/O Events. It is
     */
    private IoHandler handler;


    /**
     * The default {@link IoSessionConfig} which will be used to configure new sessions.
     */
    protected final IoSessionConfig sessionConfig;


  /**
     * Current filter chain builder.
     */
    private IoFilterChainBuilder filterChainBuilder = new DefaultIoFilterChainBuilder();


    private IoSessionDataStructureFactory sessionDataStructureFactory = new DefaultIoSessionDataStructureFactory();


    /**
     * Maintains the {@link IoServiceListener}s of this service.
     */
    private final IoServiceListenerSupport listeners;


    /**
     * A lock object which must be acquired when related resources are
     * destroyed.
     */
    protected final Object disposalLock = new Object();


    private volatile boolean disposing;


    private volatile boolean disposed;


    /**
     * {@inheritDoc}
     */
    private IoServiceStatistics stats = new IoServiceStatistics(this);

}

A helper class which provides addition and removal of  IoServiceListener and firing

在AbstractIoService 中涉及到IoServiceListenerSupport 类,来关联IoServiceListener 监听器和fire事件。IoServiceStatistics 来统计与IoSession相关数据。


public interface IoServiceListener extends EventListener {/*** Invoked when a new service is activated by an {@link IoService}.** @param service the {@link IoService}*/void serviceActivated(IoService service) throws Exception;/*** Invoked when a service is idle.*/void serviceIdle(IoService service, IdleStatus idleStatus) throws Exception;/*** Invoked when a service is deactivated by an {@link IoService}.** @param service the {@link IoService}*/void serviceDeactivated(IoService service) throws Exception;/*** Invoked when a new session is created by an {@link IoService}.** @param session the new session*/void sessionCreated(IoSession session) throws Exception;/*** Invoked when a new session is closed by an {@link IoService}.* * @param session*            the new session*/void sessionClosed(IoSession session) throws Exception;/*** Invoked when a session is being destroyed by an {@link IoService}.* * @param session*            the session to be destroyed*/void sessionDestroyed(IoSession session) throws Exception;
}

public class IoServiceListenerSupport {/** The {@link IoService} that this instance manages. */private final IoService service;/** A list of {@link IoServiceListener}s. */private final List<IoServiceListener> listeners = new CopyOnWriteArrayList<IoServiceListener>();/** Tracks managed sessions. */private final ConcurrentMap<Long, IoSession> managedSessions = new ConcurrentHashMap<Long, IoSession>();/**  Read only version of {@link #managedSessions}. */private final Map<Long, IoSession> readOnlyManagedSessions = Collections.unmodifiableMap(managedSessions);private final AtomicBoolean activated = new AtomicBoolean();/** Time this listenerSupport has been activated */private volatile long activationTime;/** A counter used to store the maximum sessions we managed since the listenerSupport has been activated */private volatile int largestManagedSessionCount = 0;/** A global counter to count the number of sessions managed since the start */private volatile long cumulativeManagedSessionCount = 0;}


Processor 处理newSession 相关逻辑。


  /*** Loops over the new sessions blocking queue and returns the number of* sessions which are effectively created** @return The number of new sessions*/private int handleNewSessions() {int addedSessions = 0;//Acceptor 线程把新链接通过并发队列放入到IoProccessor线程中。IoProccessor线程优先新链接的socketfor (S session = newSessions.poll(); session != null; session = newSessions.poll()) {if (addNow(session)) {// A new session has been createdaddedSessions++;}}return addedSessions;}

Processor 把newSession队列中的NioSession移除掉。然后IoServiceListenerSupport 执行fireSessionCreated()事件。


  /*** Process a new session :* - initialize it* - create its chain* - fire the CREATED listeners if any** @param session The session to create* @return true if the session has been registered*/private boolean addNow(S session) {boolean registered = false;//处理一个新socket的流程,初始化IoSession,创建一个handler chain 和创建监听器try {init(session);registered = true;// Build the filter chain of this session.IoFilterChainBuilder chainBuilder = session.getService().getFilterChainBuilder();chainBuilder.buildFilterChain(session.getFilterChain());// DefaultIoFilterChain.CONNECT_FUTURE is cleared inside here// in AbstractIoFilterChain.fireSessionOpened().// Propagate the SESSION_CREATED event up to the chainIoServiceListenerSupport listeners = ((AbstractIoService) session.getService()).getListeners();listeners.fireSessionCreated(session);} catch (Exception e) {ExceptionMonitor.getInstance().exceptionCaught(e);try {destroy(session);} catch (Exception e1) {ExceptionMonitor.getInstance().exceptionCaught(e1);} finally {registered = false;}}return registered;}

  /*** Calls {@link IoServiceListener#sessionCreated(IoSession)} for all registered listeners.* * @param session The session which has been created*/public void fireSessionCreated(IoSession session) {boolean firstSession = false;if (session.getService() instanceof IoConnector) {synchronized (managedSessions) {firstSession = managedSessions.isEmpty();}}// If already registered, ignore.if (managedSessions.putIfAbsent(session.getId(), session) != null) {return;}// If the first connector session, fire a virtual service activation event.if (firstSession) {fireServiceActivated();}// Fire session events.IoFilterChain filterChain = session.getFilterChain();filterChain.fireSessionCreated();filterChain.fireSessionOpened();int managedSessionCount = managedSessions.size();if (managedSessionCount > largestManagedSessionCount) {largestManagedSessionCount = managedSessionCount;}cumulativeManagedSessionCount++;// Fire listener events.for (IoServiceListener l : listeners) {try {l.sessionCreated(session);} catch (Exception e) {ExceptionMonitor.getInstance().exceptionCaught(e);}}}

Processor 线程把NioSession 放到IoServiceListenerSupport 的managedSessions 队列中。在IoServiceListenerSupport 来追踪IoSession.


    public void fireSessionCreated(IoSession session) {boolean firstSession = false;if (session.getService() instanceof IoConnector) {synchronized (managedSessions) {firstSession = managedSessions.isEmpty();}}// If already registered, ignore.if (managedSessions.putIfAbsent(session.getId(), session) != null) {return;}// If the first connector session, fire a virtual service activation event.if (firstSession) {fireServiceActivated();}// Fire session events.IoFilterChain filterChain = session.getFilterChain();filterChain.fireSessionCreated();filterChain.fireSessionOpened();int managedSessionCount = managedSessions.size();if (managedSessionCount > largestManagedSessionCount) {largestManagedSessionCount = managedSessionCount;}cumulativeManagedSessionCount++;// Fire listener events.for (IoServiceListener l : listeners) {try {l.sessionCreated(session);} catch (Exception e) {ExceptionMonitor.getInstance().exceptionCaught(e);}}}


在IoServiceListenerSupport 分别触发了fireSessionCreated(),fireSessionOpened()事件。



这篇关于Apache mina 源码再读3 I/O Service 源码剖析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/720392

相关文章

SpringBoot整合Apache Spark实现一个简单的数据分析功能

《SpringBoot整合ApacheSpark实现一个简单的数据分析功能》ApacheSpark是一个开源的大数据处理框架,它提供了丰富的功能和API,用于分布式数据处理、数据分析和机器学习等任务... 目录第一步、添加android依赖第二步、编写配置类第三步、编写控制类启动项目并测试总结ApacheS

Apache服务器IP自动跳转域名的问题及解决方案

《Apache服务器IP自动跳转域名的问题及解决方案》本教程将详细介绍如何通过Apache虚拟主机配置实现这一功能,并解决常见问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,... 目录​​问题背景​​解决方案​​方法 1:修改 httpd-vhosts.conf(推荐)​​步骤

Spring Boot分层架构详解之从Controller到Service再到Mapper的完整流程(用户管理系统为例)

《SpringBoot分层架构详解之从Controller到Service再到Mapper的完整流程(用户管理系统为例)》本文将以一个实际案例(用户管理系统)为例,详细解析SpringBoot中Co... 目录引言:为什么学习Spring Boot分层架构?第一部分:Spring Boot的整体架构1.1

java 恺撒加密/解密实现原理(附带源码)

《java恺撒加密/解密实现原理(附带源码)》本文介绍Java实现恺撒加密与解密,通过固定位移量对字母进行循环替换,保留大小写及非字母字符,由于其实现简单、易于理解,恺撒加密常被用作学习加密算法的入... 目录Java 恺撒加密/解密实现1. 项目背景与介绍2. 相关知识2.1 恺撒加密算法原理2.2 Ja

Nginx屏蔽服务器名称与版本信息方式(源码级修改)

《Nginx屏蔽服务器名称与版本信息方式(源码级修改)》本文详解如何通过源码修改Nginx1.25.4,移除Server响应头中的服务类型和版本信息,以增强安全性,需重新配置、编译、安装,升级时需重复... 目录一、背景与目的二、适用版本三、操作步骤修改源码文件四、后续操作提示五、注意事项六、总结一、背景与

Android实现图片浏览功能的示例详解(附带源码)

《Android实现图片浏览功能的示例详解(附带源码)》在许多应用中,都需要展示图片并支持用户进行浏览,本文主要为大家介绍了如何通过Android实现图片浏览功能,感兴趣的小伙伴可以跟随小编一起学习一... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

深度剖析SpringBoot日志性能提升的原因与解决

《深度剖析SpringBoot日志性能提升的原因与解决》日志记录本该是辅助工具,却为何成了性能瓶颈,SpringBoot如何用代码彻底破解日志导致的高延迟问题,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言第一章:日志性能陷阱的底层原理1.1 日志级别的“双刃剑”效应1.2 同步日志的“吞吐量杀手”

解决Nginx启动报错Job for nginx.service failed because the control process exited with error code问题

《解决Nginx启动报错Jobfornginx.servicefailedbecausethecontrolprocessexitedwitherrorcode问题》Nginx启... 目录一、报错如下二、解决原因三、解决方式总结一、报错如下Job for nginx.service failed bec

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Apache Ignite缓存基本操作实例详解

《ApacheIgnite缓存基本操作实例详解》文章介绍了ApacheIgnite中IgniteCache的基本操作,涵盖缓存获取、动态创建、销毁、原子及条件更新、异步执行,强调线程池注意事项,避免... 目录一、获取缓存实例(Getting an Instance of a Cache)示例代码:二、动态