Springboot拦截器实现IP黑名单

Springboot拦截器实现IP黑名单

一·业务场景和需要实现的功能

以redis作为IP存储地址实现。

业务场景:针对秒杀活动或者常规电商业务场景等,防止恶意脚本不停的刷接口。

实现功能:写一个拦截器拦截掉黑名单IP,额外增加一个接口,将ip地址添加到redis中,并且返回redis中当前全部ip

二·Springboot中定义一个拦截器


@Order(0)
@Aspect
@Component
public class AopInterceptor {
   


    /**
     * 定义拦截器规则
     */
    @Pointcut("execution(* com.test.test.api.controller.test.test.*(..))")
    public void pointCut() {
   
    }

      /**
     * 拦截器具体实现
     *
     * @throws Throwable
     */
    @Around(value = "pointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
   
        try {
   

            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            //判断是否为黑名单用户
            String ip = getIpAddress(request);
            if (checkIpBlack(ip)) {
   
                //ip在黑名单中返回false
                //return false;
                DefaultResponse defaultResponse = new DefaultResponse();
                defaultResponse.setCode(-1);
                defaultResponse.setMessage("ip在黑名单中,拒绝访问.");
                SysLogHelper.log("IpBlackAopInterceptor", "当前请求ip" + ip, "ip在黑名单中,拒绝访问");
                return defaultResponse;
            } else {
   
                //ip不在黑名单中返回true
                SysLogHelper.log("IpBlackAopInterceptor", "当前请求ip" + ip, "ip正常,允许访问");
                return point.proceed();
            }


        } catch (Exception e) {
   
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值