org.apache.mina.filter.executor.ExecutorFilter Java Examples

The following examples show how to use org.apache.mina.filter.executor.ExecutorFilter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Server.java    From oim-fx with MIT License 6 votes vote down vote up
public synchronized boolean startServer(int port) {
    if (running) {
        return running;
    }
    try {

        acceptor = new NioSocketAcceptor();
        acceptor.addListener(new ServerListener());
        acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new DataCodecFactory()));
        acceptor.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
        acceptor.getSessionConfig().setReadBufferSize(2048); // 设置读取数据的缓冲区大小
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);// 读写通道10秒内无操作进入空闲状态
        acceptor.setHandler(new ServerHandler()); // 绑定逻辑处理起器
        acceptor.bind(new InetSocketAddress(port));// 绑定端口
        acceptor.setReuseAddress(true);
        logger.info("服务器启动成功。。。。端口为:" + port);
        return running = true;
    } catch (IOException e) {
        logger.error("服务器启动异常。。。。", e);
        e.printStackTrace();
        running = false;
    }
    return running = false;
}
 
Example #2
Source File: CIMNioSocketAcceptor.java    From cim with Apache License 2.0 6 votes vote down vote up
private void bindWebPort() throws IOException {

		/*
		 * 预制websocket握手请求的处理
		 */
		INNER_HANDLER_MAP.put(CIMConstant.CLIENT_WEBSOCKET_HANDSHAKE, new WebsocketHandler());

		webAcceptor = new NioSocketAcceptor();
		((DefaultSocketSessionConfig) webAcceptor.getSessionConfig()).setKeepAlive(true);
		((DefaultSocketSessionConfig) webAcceptor.getSessionConfig()).setTcpNoDelay(true);
		webAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new WebMessageCodecFactory()));
		webAcceptor.getFilterChain().addLast("logger", new LoggingFilter());
		webAcceptor.getFilterChain().addLast("executor", new ExecutorFilter(createWorkerExecutor()));
		webAcceptor.setHandler(this);

		webAcceptor.bind(new InetSocketAddress(webPort));
		String logBanner = "\n\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"*                   Websocket Server started on port {}.                         *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n";
		LOGGER.info(logBanner, webPort);
	}
 
Example #3
Source File: NetManager.java    From GameServer with Apache License 2.0 6 votes vote down vote up
public  void startListner(IoHandler iohandler,int listenPort) throws Exception{
	acceptor = new NioSocketAcceptor();
	acceptor.setBacklog(100);
	acceptor.setReuseAddress(true);
	acceptor.setHandler(iohandler);
	
       DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
       IoFilter protocol = new ProtocolCodecFilter(new GameProtocolcodecFactory());
       chain.addLast("codec", protocol);
	threadpool = new OrderedThreadPoolExecutor(500);
	threadpool.setThreadFactory(new ServerThreadFactory("OrderedThreadPool"));
	chain.addLast("threadPool", new ExecutorFilter(threadpool));
	
	int recsize = 5120;
	int sendsize = 40480;                                                                                         
	int timeout = 10;
	SocketSessionConfig sc = acceptor.getSessionConfig();
	sc.setReuseAddress(true);// 设置每一个非主监听连接的端口可以重用
	sc.setReceiveBufferSize(recsize);// 设置输入缓冲区的大小
	sc.setSendBufferSize(sendsize);// 设置输出缓冲区的大小
	sc.setTcpNoDelay(true);// flush函数的调用 设置为非延迟发送,为true则不组装成大包发送,收到东西马上发出   
	sc.setSoLinger(0);
	sc.setIdleTime(IdleStatus.READER_IDLE, timeout);
	acceptor.bind(new InetSocketAddress(listenPort));
}
 
Example #4
Source File: SocketConnectorSupplier.java    From sumk with Apache License 2.0 6 votes vote down vote up
private synchronized SocketConnector create() {
	if (connector != null && !connector.isDisposing() && !connector.isDisposed()) {
		return connector;
	}
	try {
		NioSocketConnector con = new NioSocketConnector(
				AppInfo.getInt("sumk.rpc.client.poolsize", Runtime.getRuntime().availableProcessors() + 1));
		con.setConnectTimeoutMillis(AppInfo.getInt("sumk.rpc.connect.timeout", 5000));
		con.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, AppInfo.getInt(Const.SOA_SESSION_IDLE, 600));
		con.setHandler(createClientHandler());
		con.getFilterChain().addLast("codec", new ProtocolCodecFilter(IOC.get(SumkCodecFactory.class)));
		if (AppInfo.getBoolean("sumk.rpc.client.threadpool.enable", true)) {
			con.getFilterChain().addLast("threadpool", new ExecutorFilter(SoaExcutors.getClientThreadPool()));
		}
		this.connector = con;
		return con;
	} catch (Exception e) {
		Logs.rpc().error(e.getMessage(), e);
		throw new SumkException(5423654, "create connector error", e);
	}
}
 
Example #5
Source File: HttpServer.java    From game-server with MIT License 5 votes vote down vote up
@Override
public void run() {
	DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
	chain.addLast("codec", new HttpServerCodecImpl());

	// // 线程队列池
	OrderedThreadPoolExecutor threadpool = new OrderedThreadPoolExecutor(minaServerConfig.getOrderedThreadPoolExecutorSize());
	chain.addLast("threadPool", new ExecutorFilter(threadpool));

	acceptor.setReuseAddress(minaServerConfig.isReuseAddress()); // 允许地址重用

	SocketSessionConfig sc = acceptor.getSessionConfig();
	sc.setReuseAddress(minaServerConfig.isReuseAddress());
	sc.setReceiveBufferSize(minaServerConfig.getMaxReadSize());
	sc.setSendBufferSize(minaServerConfig.getSendBufferSize());
	sc.setTcpNoDelay(minaServerConfig.isTcpNoDelay());
	sc.setSoLinger(minaServerConfig.getSoLinger());
	sc.setIdleTime(IdleStatus.READER_IDLE, minaServerConfig.getReaderIdleTime());
	sc.setIdleTime(IdleStatus.WRITER_IDLE, minaServerConfig.getWriterIdleTime());

	acceptor.setHandler(ioHandler);

	try {
		acceptor.bind(new InetSocketAddress(minaServerConfig.getHttpPort()));
		LOG.warn("已开始监听HTTP端口:{}", minaServerConfig.getHttpPort());
	} catch (IOException e) {
		SysUtil.exit(getClass(), e, "监听HTTP端口:{}已被占用", minaServerConfig.getHttpPort());
	}
}
 
Example #6
Source File: UdpServer.java    From game-server with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void run() {
	synchronized (this) {
		if (!isRunning) {
			DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
			if (factory == null) {
				factory = new DefaultProtocolCodecFactory();
			}
			factory.getDecoder().setMaxReadSize(minaServerConfig.getMaxReadSize());
			factory.getEncoder().setMaxScheduledWriteMessages(minaServerConfig.getMaxScheduledWriteMessages());
			chain.addLast("codec", new ProtocolCodecFilter(factory));
			threadpool = new OrderedThreadPoolExecutor(minaServerConfig.getOrderedThreadPoolExecutorSize());
			chain.addLast("threadPool", new ExecutorFilter(threadpool));
			if(filters != null){
                   filters.forEach((key, filter)->chain.addLast(key, filter));
			}

			DatagramSessionConfig dc = acceptor.getSessionConfig();
			dc.setReuseAddress(minaServerConfig.isReuseAddress());
			dc.setReceiveBufferSize(minaServerConfig.getReceiveBufferSize());
			dc.setSendBufferSize(minaServerConfig.getSendBufferSize());
			dc.setIdleTime(IdleStatus.READER_IDLE, minaServerConfig.getReaderIdleTime());
			dc.setIdleTime(IdleStatus.WRITER_IDLE, minaServerConfig.getWriterIdleTime());
			dc.setBroadcast(true);
			dc.setCloseOnPortUnreachable(true);

			acceptor.setHandler(ioHandler);
			try {
				acceptor.bind(new InetSocketAddress(minaServerConfig.getPort()));
				LOGGER.warn("已开始监听UDP端口:{}", minaServerConfig.getPort());
			} catch (IOException e) {
				LOGGER.warn("监听UDP端口:{}已被占用", minaServerConfig.getPort());
				LOGGER.error("UDP, 服务异常", e);
			}
		}
	}
}
 
Example #7
Source File: MinaStartup.java    From seed with Apache License 2.0 5 votes vote down vote up
public final void bind() throws IOException {
    NioSocketAcceptor acceptor = new NioSocketAcceptor();
    //这里并未配置backlog,那么它会采用操作系统默认的连接请求队列长度50
    //详见org.apache.mina.core.polling.AbstractPollingIoAcceptor类源码的96行
    //acceptor.setBacklog(0);
    acceptor.setReuseAddress(this.reuseAddress);
    acceptor.getSessionConfig().setWriteTimeout(this.writeTimeout);
    acceptor.getSessionConfig().setBothIdleTime(this.bothIdleTime);
    //这里有个鱼和熊掌不可兼得的情景
    //若将codec定义在executor的前面,则codec由NioProcessor-1线程处理,IoHandler由pool-1-thread-1线程处理
    //若将codec定义在executor的后面,则codec和IoHandler都由pool-1-thread-1线程处理
    acceptor.getFilterChain().addLast("logger", new LoggingFilter());
    acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ServerProtocolCodecFactory()));
    acceptor.getFilterChain().addLast("executor", new ExecutorFilter());
    //注意:无论如何executor都要定义在NioSocketConnector.setHandler()的前面
    acceptor.setHandler(this.handler);
    if(null==this.socketAddresses || this.socketAddresses.size()<1){
        throw new RuntimeException("监听SocketAddress数不得小于1");
    }
    acceptor.bind(this.socketAddresses);
    if(acceptor.isActive()){
        System.out.println("写 超 时: " + this.writeTimeout + "ms");
        System.out.println("发呆配置: Both Idle " + this.bothIdleTime + "s");
        System.out.println("端口重用: " + this.reuseAddress);
        System.out.println("服务端初始化完成...");
        System.out.println("服务已启动...开始监听..." + acceptor.getLocalAddresses());
    }else{
        System.out.println("服务端初始化失败...");
    }
}
 
Example #8
Source File: FilterChainBuilder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public FilterChainBuilder ( final boolean clientMode )
{
    if ( !Boolean.getBoolean ( "org.eclipse.scada.protocol.ngp.common.disableStats" ) )
    {
        this.filters.add ( new Entry ( StatisticsFilter.DEFAULT_NAME, new StatisticsFilter () ) );
    }

    this.filters.add ( new Entry ( "logger.raw", new LoggerFilterFactory ( "raw" ) ) );

    this.filters.add ( new Entry ( "ssl" ) );
    this.filters.add ( new Entry ( "streamCompression" ) );

    this.filters.add ( new Entry ( "logger", new LoggerFilterFactory ( "pre" ) ) );

    this.filters.add ( new Entry ( "sync", new ExecutorFilter ( Integer.getInteger ( "org.eclipse.scada.protocol.ngp.common.coreSessionThreads", 0 ), Integer.getInteger ( "org.eclipse.scada.protocol.ngp.common.maxSessionThreads", 1 ), 1, TimeUnit.MINUTES, new NamedThreadFactory ( "org.eclipse.scada.protocol.ngp.common.FilterChainSync", false, true, THREAD_COUNTER ), IoEventType.WRITE ) ) );
    this.filters.add ( new Entry ( "frameCodec", new ProtocolCodecFilter ( new FrameEncoder (), new FrameDecoder () ) ) );

    this.filters.add ( new Entry ( "keepalive" ) );

    this.filters.add ( new Entry ( "messageChannelCodec", new MessageChannelCodecFilter () ) );
    this.filters.add ( new Entry ( "messageChannel", new IoFilterFactoryAdapter () {

        @Override
        public IoFilter create ()
        {
            // we need new instances of MessageChannelFilter
            return new MessageChannelFilter ( clientMode );
        }
    } ) );
}
 
Example #9
Source File: MinaServer.java    From JobX with Apache License 2.0 5 votes vote down vote up
@Override
public void start(final int port,final ServerHandler handler) {

    this.serverDaemon = new Thread(new Runnable() {
        @Override
        public void run() {
            final MinaServerHandler serverHandler = new MinaServerHandler(handler);
            socketAddress = new InetSocketAddress(port);

            acceptor = new NioSocketAcceptor();
            acceptor.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
            acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaCodecAdapter(Response.class, Request.class)));
            acceptor.setHandler(serverHandler);
            try {
                acceptor.bind(socketAddress);
                if (logger.isInfoEnabled()) {
                    logger.info("[JobX] MinaServer start at address:{} success", port);
                }
            } catch (IOException e) {
                logger.error("[JobX] MinaServer start failure: {}", stackTrace(e));
            }
        }
    });
    this.serverDaemon.setDaemon(true);
    this.serverDaemon.start();

    threadPoolExecutor = new ThreadPoolExecutor(50, 100, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
        private final AtomicInteger idGenerator = new AtomicInteger(0);
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "MinaServer" + this.idGenerator.incrementAndGet());
        }
    });

}
 
Example #10
Source File: CIMNioSocketAcceptor.java    From cim with Apache License 2.0 5 votes vote down vote up
private void bindAppPort() throws IOException {


		appAcceptor = new NioSocketAcceptor();
		((DefaultSocketSessionConfig) appAcceptor.getSessionConfig()).setKeepAlive(true);
		((DefaultSocketSessionConfig) appAcceptor.getSessionConfig()).setTcpNoDelay(true);

		KeepAliveFilter keepAliveFilter = new KeepAliveFilter(this, IdleStatus.BOTH_IDLE);
		keepAliveFilter.setRequestInterval(IDLE_HEART_REQUEST_TIME);
		keepAliveFilter.setRequestTimeout(HEART_RESPONSE_TIME_OUT);
		keepAliveFilter.setForwardEvent(true);

		appAcceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new AppMessageCodecFactory()));
		appAcceptor.getFilterChain().addLast("logger", new LoggingFilter());
		appAcceptor.getFilterChain().addLast("heartbeat", keepAliveFilter);
		appAcceptor.getFilterChain().addLast("executor", new ExecutorFilter(createWorkerExecutor()));
		appAcceptor.setHandler(this);

		appAcceptor.bind(new InetSocketAddress(appPort));
		String logBanner = "\n\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"*                   App Socket Server started on port {}.                        *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n";
		LOGGER.info(logBanner, appPort);
	}
 
Example #11
Source File: Application.java    From CXTouch with GNU General Public License v3.0 4 votes vote down vote up
private void createDeviceConnector() {
    NioSocketConnector connector = new NioSocketConnector();

    connector.setHandler(new DeviceIoHandlerAdapter(this));
    connector.getFilterChain().addLast("codec", new ProtocolCodecFilter( new DSCodecFactory()));
    connector.getFilterChain().addLast("threadModel", new ExecutorFilter(executors));

    deviceConnector = connector;

    NioSocketConnector scriptConnector = new NioSocketConnector();

    scriptConnector.setHandler(new ScriptDeviceIoHandlerAdapter(this));
    scriptConnector.getFilterChain().addLast("codec", new ProtocolCodecFilter( new DSCodecFactory()));
    scriptConnector.getFilterChain().addLast("threadModel", new ExecutorFilter(executors));

    scriptDeviceConnector = scriptConnector;


}
 
Example #12
Source File: TcpServer.java    From game-server with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public void run() {
    synchronized (this) {
        if (!isRunning) {
            isRunning = true;
            DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
            if (factory == null) {
                factory = new DefaultProtocolCodecFactory();
            }

            if (factory instanceof DefaultProtocolCodecFactory) {
                ProtocolCodecFactoryImpl defaultFactory = (ProtocolCodecFactoryImpl) factory;
                defaultFactory.getDecoder().setMaxReadSize(minaServerConfig.getMaxReadSize());
                defaultFactory.getEncoder()
                              .setMaxScheduledWriteMessages(minaServerConfig.getMaxScheduledWriteMessages());
            }

            chain.addLast("codec", new ProtocolCodecFilter(factory));
            threadpool = new OrderedThreadPoolExecutor(minaServerConfig.getOrderedThreadPoolExecutorSize());
            chain.addLast("threadPool", new ExecutorFilter(threadpool));
            if (filters != null) {
                filters.forEach((key, filter) -> {
                    if ("ssl".equalsIgnoreCase(key) || "tls".equalsIgnoreCase(key)) { // ssl过滤器必须添加到首部
                        chain.addFirst(key, filter);
                    } else {
                        chain.addLast(key, filter);
                    }
                });
            }

            acceptor.setReuseAddress(minaServerConfig.isReuseAddress()); // 允许地址重用

            SocketSessionConfig sc = acceptor.getSessionConfig();
            sc.setReuseAddress(minaServerConfig.isReuseAddress());
            sc.setReceiveBufferSize(minaServerConfig.getReceiveBufferSize());
            sc.setSendBufferSize(minaServerConfig.getSendBufferSize());
            sc.setTcpNoDelay(minaServerConfig.isTcpNoDelay());
            sc.setSoLinger(minaServerConfig.getSoLinger());
            sc.setIdleTime(IdleStatus.READER_IDLE, minaServerConfig.getReaderIdleTime());
            sc.setIdleTime(IdleStatus.WRITER_IDLE, minaServerConfig.getWriterIdleTime());

            acceptor.setHandler(ioHandler);

            try {
                acceptor.bind(new InetSocketAddress(minaServerConfig.getPort()));
                log.warn("已开始监听TCP端口:{}", minaServerConfig.getPort());
            } catch (IOException e) {
                log.warn("监听TCP端口:{}已被占用", minaServerConfig.getPort());
                log.error("TCP 服务异常", e);
            }
        }
    }
}
 
Example #13
Source File: RemoteConnector.java    From oim-fx with MIT License 4 votes vote down vote up
private void initConnector() {
	ioConnector = new NioSocketConnector();
	ioConnector.getFilterChain().addLast("mis", new ProtocolCodecFilter(new BytesDataFactory()));// 添加过滤器
	ioConnector.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
	ioConnector.setHandler(handler);// 添加业务逻辑处理类
}
 
Example #14
Source File: SocketConnector.java    From oim-fx with MIT License 4 votes vote down vote up
private void initConnector() {
	ioConnector = new NioSocketConnector();
	ioConnector.getFilterChain().addLast("mis", new ProtocolCodecFilter(new DataCodecFactory()));// 添加过滤器
	ioConnector.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
	ioConnector.setHandler(handler);// 添加业务逻辑处理类
}
 
Example #15
Source File: MINAConnectionAcceptor.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Starts this acceptor by binding the socket acceptor. When the acceptor is already started, a warning will be
 * logged and the method invocation is otherwise ignored.
 */
@Override
public synchronized void start()
{
    if ( socketAcceptor != null )
    {
        Log.warn( "Unable to start acceptor (it is already started!)" );
        return;
    }

    try
    {
        // Configure the thread pool that is to be used.
        final int initialSize = ( configuration.getMaxThreadPoolSize() / 4 ) + 1;
        final ExecutorFilter executorFilter = new ExecutorFilter( initialSize, configuration.getMaxThreadPoolSize(), 60, TimeUnit.SECONDS );
        final ThreadPoolExecutor eventExecutor = (ThreadPoolExecutor) executorFilter.getExecutor();
        final ThreadFactory threadFactory = new NamedThreadFactory( name + "-thread-", eventExecutor.getThreadFactory(), true, null );
        eventExecutor.setThreadFactory( threadFactory );

        // Construct a new socket acceptor, and configure it.
        socketAcceptor = buildSocketAcceptor();

        if ( JMXManager.isEnabled() )
        {
            configureJMX( socketAcceptor, name );
        }

        final DefaultIoFilterChainBuilder filterChain = socketAcceptor.getFilterChain();
        filterChain.addFirst( ConnectionManagerImpl.EXECUTOR_FILTER_NAME, executorFilter );

        // Add the XMPP codec filter
        filterChain.addAfter( ConnectionManagerImpl.EXECUTOR_FILTER_NAME, ConnectionManagerImpl.XMPP_CODEC_FILTER_NAME, new ProtocolCodecFilter( new XMPPCodecFactory() ) );

        // Kill sessions whose outgoing queues keep growing and fail to send traffic
        filterChain.addAfter( ConnectionManagerImpl.XMPP_CODEC_FILTER_NAME, ConnectionManagerImpl.CAPACITY_FILTER_NAME, new StalledSessionsFilter() );

        // Ports can be configured to start connections in SSL (as opposed to upgrade a non-encrypted socket to an encrypted one, typically using StartTLS)
        if ( configuration.getTlsPolicy() == Connection.TLSPolicy.legacyMode )
        {
            final SslFilter sslFilter = encryptionArtifactFactory.createServerModeSslFilter();
            filterChain.addAfter( ConnectionManagerImpl.EXECUTOR_FILTER_NAME, ConnectionManagerImpl.TLS_FILTER_NAME, sslFilter );
        }

        // Throttle sessions who send data too fast
        if ( configuration.getMaxBufferSize() > 0 )
        {
            socketAcceptor.getSessionConfig().setMaxReadBufferSize( configuration.getMaxBufferSize() );
            Log.debug( "Throttling read buffer for connections to max={} bytes", configuration.getMaxBufferSize() );
        }

        // Start accepting connections
        socketAcceptor.setHandler( connectionHandler );
        socketAcceptor.bind( new InetSocketAddress( configuration.getBindAddress(), configuration.getPort() ) );
    }
    catch ( Exception e )
    {
        System.err.println( "Error starting " + configuration.getPort() + ": " + e.getMessage() );
        Log.error( "Error starting: " + configuration.getPort(), e );
        // Reset for future use.
        if (socketAcceptor != null) {
            try {
                socketAcceptor.unbind();
            } finally {
                socketAcceptor = null;
            }
        }
    }
}
 
Example #16
Source File: MINAConnectionAcceptor.java    From Openfire with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void reconfigure( ConnectionConfiguration configuration )
{
    this.configuration = configuration;

    if ( socketAcceptor == null )
    {
        return; // reconfig will occur when acceptor is started.
    }

    final DefaultIoFilterChainBuilder filterChain = socketAcceptor.getFilterChain();

    if ( filterChain.contains( ConnectionManagerImpl.EXECUTOR_FILTER_NAME ) )
    {
        final ExecutorFilter executorFilter = (ExecutorFilter) filterChain.get( ConnectionManagerImpl.EXECUTOR_FILTER_NAME );
        ( (ThreadPoolExecutor) executorFilter.getExecutor()).setCorePoolSize( ( configuration.getMaxThreadPoolSize() / 4 ) + 1 );
        ( (ThreadPoolExecutor) executorFilter.getExecutor()).setMaximumPoolSize( ( configuration.getMaxThreadPoolSize() ) );
    }

    if ( configuration.getTlsPolicy() == Connection.TLSPolicy.legacyMode )
    {
        // add or replace TLS filter (that's used only for 'direct-TLS')
        try
        {
            final SslFilter sslFilter = encryptionArtifactFactory.createServerModeSslFilter();
            if ( filterChain.contains( ConnectionManagerImpl.TLS_FILTER_NAME ) )
            {
                filterChain.replace( ConnectionManagerImpl.TLS_FILTER_NAME, sslFilter );
            }
            else
            {
                filterChain.addAfter( ConnectionManagerImpl.EXECUTOR_FILTER_NAME, ConnectionManagerImpl.TLS_FILTER_NAME, sslFilter );
            }
        }
        catch ( KeyManagementException | NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException e )
        {
            Log.error( "An exception occurred while reloading the TLS configuration.", e );
        }
    }
    else
    {
        // The acceptor is in 'startTLS' mode. Remove TLS filter (that's used only for 'direct-TLS')
        if ( filterChain.contains( ConnectionManagerImpl.TLS_FILTER_NAME ) )
        {
            filterChain.remove( ConnectionManagerImpl.TLS_FILTER_NAME );
        }
    }

    if ( configuration.getMaxBufferSize() > 0 )
    {
        socketAcceptor.getSessionConfig().setMaxReadBufferSize( configuration.getMaxBufferSize() );
        Log.debug( "Throttling read buffer for connections to max={} bytes", configuration.getMaxBufferSize() );
    }
}
 
Example #17
Source File: MINAStatCollector.java    From Openfire with Apache License 2.0 4 votes vote down vote up
@Override 
public void run()
{
    while ( !stop )
    {
        // wait polling time
        try
        {
            Thread.sleep( pollingInterval );
        }
        catch ( InterruptedException e )
        {
            Log.trace("Sleep interrupted");
        }

        long tmpMsgWritten = 0L;
        long tmpMsgRead = 0L;
        long tmpBytesWritten = 0L;
        long tmpBytesRead = 0L;
        long tmpScheduledWrites = 0L;
        long tmpQueuevedEvents = 0L;

        for (IoSession session : polledSessions)
        {
            // upadating individual session statistics
            IoSessionStat sessStat = ( IoSessionStat ) session.getAttribute( KEY );

            long currentTimestamp = System.currentTimeMillis();
            // Calculate delta
            float pollDelta = (currentTimestamp - sessStat.lastPollingTime) / 1000f;
            // Store last polling time of this session
            sessStat.lastPollingTime = currentTimestamp;

            long readBytes = session.getReadBytes();
            long writtenBytes = session.getWrittenBytes();
            long readMessages = session.getReadMessages();
            long writtenMessages = session.getWrittenMessages();
            sessStat.byteReadThroughput = (readBytes - sessStat.lastByteRead) / pollDelta;
            sessStat.byteWrittenThroughput = (writtenBytes - sessStat.lastByteWrite) / pollDelta;
            sessStat.messageReadThroughput = (readMessages - sessStat.lastMessageRead) / pollDelta;
            sessStat.messageWrittenThroughput = (writtenMessages - sessStat.lastMessageWrite) / pollDelta;

            tmpMsgWritten += (writtenMessages - sessStat.lastMessageWrite);
            tmpMsgRead += (readMessages - sessStat.lastMessageRead);
            tmpBytesWritten += (writtenBytes - sessStat.lastByteWrite);
            tmpBytesRead += (readBytes - sessStat.lastByteRead);
            tmpScheduledWrites += session.getScheduledWriteMessages();

            ExecutorFilter executorFilter =
                    (ExecutorFilter) session.getFilterChain().get(EXECUTOR_FILTER_NAME);
            if (executorFilter != null) {
                Executor executor =  executorFilter.getExecutor();
                if (executor instanceof OrderedThreadPoolExecutor) {
                    tmpQueuevedEvents += ((OrderedThreadPoolExecutor) executor).getActiveCount();
                }
            }

            sessStat.lastByteRead = readBytes;
            sessStat.lastByteWrite = writtenBytes;
            sessStat.lastMessageRead = readMessages;
            sessStat.lastMessageWrite = writtenMessages;

        }

        totalMsgWritten.addAndGet(tmpMsgWritten);
        totalMsgRead.addAndGet(tmpMsgRead);
        totalBytesWritten.addAndGet(tmpBytesWritten);
        totalBytesRead.addAndGet(tmpBytesRead);
        totalScheduledWrites.set(tmpScheduledWrites);
        totalQueuedEvents.set(tmpQueuevedEvents);
    }
}
 
Example #18
Source File: NetConnector.java    From oim-fx with MIT License 4 votes vote down vote up
private void initConnector() {
    ioConnector = new NioSocketConnector();
    ioConnector.getFilterChain().addLast("mis", new ProtocolCodecFilter(new DataCodecFactory()));// 添加过滤器
    ioConnector.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
    ioConnector.setHandler(handler);// 添加业务逻辑处理类
}