当前位置:   article > 正文

Springboot拦截器IP防刷 + IP黑名单功能_spring boot拦截器实现ip黑名单

spring boot拦截器实现ip黑名单

为了方便查看 尽量把方法都放到一个文件内

先创建一个WebMvcConfigurer

@Configuration
@EnableConfigurationProperties(FileUploadProperties.class)
public class WebMvcConfigurer extends WebMvcConfigurationSupport {

	// 前面省略...
	
	@Bean
    public UserUrlInterceptor userUrlInterceptor() {
        return new UserUrlInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(userUrlInterceptor()).addPathPatterns("/**").excludePathPatterns("/sys/getVerifyToBase");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

接下来进入拦截器内部 UserUrlInterceptor

@Component
public class UserUrlInterceptor implements HandlerInterceptor {

    private static final int time = 30000;
    private static final int count = 10;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private BlacklistService blacklistService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求的url
        String url = request.getRequestURI();
        String ip = IPUtils.getIpAddr(request);

        BlacklistEntity domain = blacklistService.getByIP(ip);
        if (domain != null) {
            domain.setDisableTime(new Date(new Date().getTime() + 300000));
            blacklistService.saveOrUpdate(domain);
            throw new BusinessException(BaseResponseCode.IP_BANNED.getCode(), BaseResponseCode.IP_BANNED.getMsg());
        };

        StringBuilder sb = new StringBuilder();
        sb.append("crazeidea:").append(ip).append(url);
        // 先查询redis中是否有这个键
        String key = sb.toString().replaceAll("/", ".");
        String value = get(key);
        if (StringUtils.isBlank(value)) {
            // 为空则插入新数据
            set(key, "1", time);
        } else {
            if ("/website/other/contactus".equals(request.getRequestURI())) {
                // 为联系我们的时候 不能重复提交
                set(key, "1", 60000 * 10);
                throw new BusinessException(BaseResponseCode.CONTACT_US.getCode(), BaseResponseCode.CONTACT_US.getMsg());
            }
            if (Integer.parseInt(value) < count) {
                // 没有超过就累加
                long redisTime = getExpire(key);
                set(key, (Integer.parseInt(value) + 1) + "", Math.toIntExact(redisTime));
            } else {
                // 超过访问次数
                String cou = get(ip);
                if (StringUtils.isBlank(cou)) {
                    setNoTime(ip, "1");
                } else {
                    if (Integer.parseInt(cou) <= 5) {
                        setNoTime(ip, (Integer.parseInt(cou) + 1) + "");
                    } else {
                        // 超过访问次数 5次以上 进入黑名单
                        blacklistService.save(init(ip));
                        del(ip);
                    }
                }
                throw new BusinessException(BaseResponseCode.LIMIT_ERROR_USER.getCode(), BaseResponseCode.LIMIT_ERROR_USER.getMsg());
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }

    public BlacklistEntity init(String ip) {
        BlacklistEntity domain = new BlacklistEntity();
        domain.setIp(ip);
        domain.setDisableTime(new Date(new Date().getTime() + 300000));
        return domain;
    }

    // 根据key获取value
    public String get(String key) {
        return this.redisTemplate.opsForValue().get(key);
    }

    // 根据key删除数据
    public void del(String key) {
        boolean boo = this.redisTemplate.hasKey(key);
        if (boo) {
            this.redisTemplate.delete(key);
        }
    }

    // 向redis存入数据
    public void setNoTime(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    // 向redis存入数据 带失效时间
    public void set (String key, String value, int redisTime) {
        redisTemplate.opsForValue().set(key, value);
        redisTemplate.expire(key, redisTime, TimeUnit.MILLISECONDS);
    }

    // 获取redis当前键的失效时间
    public Long getExpire(String key) {
        if (null == key) {
            throw new BusinessException(BaseResponseCode.DATA_ERROR.getCode(), "key or TomeUnit 不能为空");
        }
        return redisTemplate.getExpire(key, TimeUnit.MILLISECONDS);
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115

接下来就是黑名单了 创建BlackListEntity实体

@Data
@TableName("blacklist")
public class BlacklistEntity extends BaseEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 主键
	 */
	@TableId("id")
	@ApiModelProperty(value = "id")
	private String id;

	/**
	 * IP
	 */
	@TableField("ip")
	@ApiModelProperty(value = "ip")
	private String ip;

	/**
	 * 黑名单结束时间
	 */
	@TableField("disable_time")
	@ApiModelProperty(value = "disable_time")
	private Date disableTime;

	/**
	 * 创建时间
	 */
	@TableField("create_time")
	@ApiModelProperty(value = "create_time")
	private Date createTime;

	/**
	 * 更新时间
	 */
	@TableField("update_time")
	@ApiModelProperty(value = "update_time")
	private Date updateTime;

	/**
	 * 是否删除(1未删除;0已删除)
	 */
	@TableField("deleted")
	@ApiModelProperty(value = "deleted")
	private Integer deleted;


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

数据库表设计

CREATE TABLE `blacklist` (
  `id` varchar(64) NOT NULL COMMENT '主键',
  `ip` varchar(255) DEFAULT NULL COMMENT 'IP',
  `disable_time` datetime DEFAULT NULL COMMENT '黑名单结束时间',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `update_time` datetime DEFAULT NULL COMMENT '更新时间',
  `deleted` tinyint(4) DEFAULT '1' COMMENT '是否删除(1未删除;0已删除)',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='IP黑名单';
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

使用mybatis-plus
感谢观看!!!如果喜欢望一键三连 0v0

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/503417
推荐阅读
相关标签
  

闽ICP备14008679号