redis 实现 ip 限制

阅读更多

 

参考:http://843977358.iteye.com/blog/2317810

          http://843977358.iteye.com/blog/2318143

 

本文 主要 是想更方便的实现ip限制,感觉楼主843977358 写的太过复杂,然后建议他用redis 或者memcached ,

因为都有expired  方法,楼主没有使用,本人就写一个吧 。。。

  


redis 实现 ip 限制_第1张图片
 

 

 

 

 

 

/*

 * Project: springmvchibernate
 * 
 * File Created at 2016年11月4日
 * 
 * Copyright 2016 CMCC Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ZYHY Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license.
 */
package com.curiousby.baoyou.cn.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.curiousby.baoyou.cn.redis.RedisConnectionContext;

/**
 * @com.curiousby.baoyou.cn.filters.IPFilter
 * @Type IPFilter.java
 * @Desc 
 * @author cmcc-B100036
 * @date 2016年11月4日 上午10:42:42
 * @version 
 */
@Component
public class IPFilter  implements Filter {

    protected static final Logger logger = LoggerFactory.getLogger(IPFilter.class);
 
    private RedisConnectionContext  redisConnectionContext;
    
    public final static int IPMAXCOUNTPERMINUTES = 5;
    public final static int IPLIMITSENCONDS = 300;
    public final static int IPCOUNTSENCONDS = 60;
    
    
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
      
        
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request; 
        WebApplicationContext wac=WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
        redisConnectionContext = (RedisConnectionContext) wac.getBean("redisConnectionContext");
        
        String ip = getIpAddr(req); 

        String ipLimit = redisConnectionContext.getValue(ip+"_limit");
        if (ipLimit !=null &&  !"".equals(ipLimit)) {
            req.getRequestDispatcher("/web/static/forward").forward(req, response);
            return;
        }else{
            String ipConut = redisConnectionContext.getValue(ip+"_count");
            if (ipConut !=null &&  !"".equals(ipConut)){
                int ipLCount = Integer.parseInt(ipConut);
                if(ipLCount >= IPMAXCOUNTPERMINUTES){
                    redisConnectionContext.setValue(ip+"_limit", ipLCount+"", IPLIMITSENCONDS);
                    redisConnectionContext.setValue(ip+"_count", "0", IPCOUNTSENCONDS); 
                    req.getRequestDispatcher("/web/static/forward").forward(req, response);
                    return;
                }else{
                    ipLCount += 1; 
                    redisConnectionContext.setValue(ip+"_count", ipLCount+"", IPCOUNTSENCONDS); 
                } 
            }else{
                redisConnectionContext.setValue(ip+"_count", "1", IPCOUNTSENCONDS);
            }
        } 
        chain.doFilter(req, response);
    }

    @Override
    public void destroy() {
         
        
    }
    
    
    public String getIpAddr(HttpServletRequest request) {   
        String ip = request.getHeader("x-forwarded-for");   
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
            ip = request.getHeader("Proxy-Client-IP");   
        }   
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
            ip = request.getHeader("WL-Proxy-Client-IP");   
        }   
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
            ip = request.getRemoteAddr();   
        }   
        return ip;   
    } 

}


/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2016年11月4日 cmcc-B100036 creat
 */

 

 

 

expire 方法

 

 public boolean setValue(final String paramKey, final String paramValue,final int seconds) {
        if (null == paramKey || null == paramValue) {
            return false;
        }
        boolean reltValue = false;
        ShardedJedis localShardedJedis = null;
        try {
            localShardedJedis = this.getRedisConnection();
            if (null != localShardedJedis) {
                localShardedJedis.set(paramKey, paramValue);  
                localShardedJedis.expire(paramKey, seconds);
            } else {
                log.error("setValue : key: " + paramKey + " null ShardedJedis error");
            }
        } catch (Exception e) {
            log.error("setValue Exception");
            e.printStackTrace();
        } finally {
            this.closeRedisConnection(localShardedJedis);
        }
        return reltValue;
    }

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。


redis 实现 ip 限制_第2张图片redis 实现 ip 限制_第3张图片redis 实现 ip 限制_第4张图片
 
 
 谢谢您的赞助,我会做的更好!

 

 

 

 

 

  • redis 实现 ip 限制_第5张图片
  • 大小: 43.1 KB
  • 查看图片附件

你可能感兴趣的:(redis,ip,限制)