MINA源码分析---对客户端设置连接间隔时间的过滤器


如果这个IP此次发起连接距离上次发起连接的时间少于规定的时间,则关闭会话,否则建立会话,可以避免同一个远程主机在短时间内发起多个连接


下面是源代码,比较简单明了,不作解释了

/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */
package org.apache.mina.filter.firewall;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A {@link IoFilter} which blocks connections from connecting
 * at a rate faster than the specified interval.
 *这个过滤器指定同一个IP 地址(不含端口号)上的请求在多长的毫秒值内可以有一个请求,
 *如果小于指定的时间间隔就有连续两个请求,那么第二个请求将被忽略
 * 
 */
public class ConnectionThrottleFilter extends IoFilterAdapter {
    private static final long DEFAULT_TIME = 1000;

    private long allowedInterval;

    private final Map<String, Long> clients;

    private final static Logger LOGGER = LoggerFactory.getLogger(ConnectionThrottleFilter.class);
    /**
     * Default constructor.  Sets the wait time to 1 second
     */
    public ConnectionThrottleFilter() {
        this(DEFAULT_TIME);
    }

    /**
     * Constructor that takes in a specified wait time.
     *
     * @param allowedInterval
     *     The number of milliseconds a client is allowed to wait
     *     before making another successful connection
     *
     */
    public ConnectionThrottleFilter(long allowedInterval) {
        this.allowedInterval = allowedInterval;
        clients = Collections.synchronizedMap(new HashMap<String, Long>());
    }

    /**
     * Sets the interval between connections from a client.
     * This value is measured in milliseconds.
     *
     * @param allowedInterval
     *     The number of milliseconds a client is allowed to wait
     *     before making another successful connection
     */
    public void setAllowedInterval(long allowedInterval) {
        this.allowedInterval = allowedInterval;
    }

    /**
     * Method responsible for deciding if a connection is OK
     * to continue
     *
     * @param session
     *     The new session that will be verified
     * @return
     *     True if the session meets the criteria, otherwise false
     */
    protected boolean isConnectionOk(IoSession session) {
        SocketAddress remoteAddress = session.getRemoteAddress();
        if (remoteAddress instanceof InetSocketAddress) {
            InetSocketAddress addr = (InetSocketAddress) remoteAddress;
            long now = System.currentTimeMillis();

            if (clients.containsKey(addr.getAddress().getHostAddress())) {

                LOGGER.debug("This is not a new client");
                Long lastConnTime = clients.get(addr.getAddress()
                        .getHostAddress());

                clients.put(addr.getAddress().getHostAddress(), now);

                // if the interval between now and the last connection is
                // less than the allowed interval, return false
                if (now - lastConnTime < allowedInterval) {
                    LOGGER.warn("Session connection interval too short");
                    return false;
                }
                
                return true;
            }

            clients.put(addr.getAddress().getHostAddress(), now);
            return true;
        }

        return false;
    }

    @Override
    public void sessionCreated(NextFilter nextFilter, IoSession session)
            throws Exception {
        if (!isConnectionOk(session)) {
            LOGGER.warn("Connections coming in too fast; closing.");
            session.close(true);
        }//满足要求才在过滤链中传递,否则关闭会话
        nextFilter.sessionCreated(session);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值