001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package io.jboot.components.limiter.interceptor;
017
018
019import com.jfinal.aop.Interceptor;
020import com.jfinal.aop.Invocation;
021import io.jboot.components.limiter.LimitType;
022import io.jboot.components.limiter.LimiterManager;
023import io.jboot.utils.RequestUtil;
024
025public class LimiterGlobalInterceptor extends BaseLimiterInterceptor implements Interceptor {
026
027
028    @Override
029    public void intercept(Invocation inv) {
030        LimiterManager manager = LimiterManager.me();
031        if (inv.isActionInvocation() && manager.isInIpWhitelist(RequestUtil.getIpAddress(inv.getController().getRequest()))) {
032            inv.invoke();
033        } else {
034            String packageOrTarget = getPackageOrTarget(inv);
035            LimiterManager.LimitConfigBean configBean = manager.matchConfig(packageOrTarget);
036            if (configBean != null) {
037                doInterceptByTypeAndRate(configBean, packageOrTarget, inv);
038            } else {
039                inv.invoke();
040            }
041        }
042    }
043
044
045    private void doInterceptByTypeAndRate(LimiterManager.LimitConfigBean limitConfigBean, String resource, Invocation inv) {
046        switch (limitConfigBean.getType()) {
047            case LimitType.CONCURRENCY:
048                doInterceptForConcurrency(limitConfigBean.getRate(), resource, null, inv);
049                break;
050            case LimitType.IP_CONCURRENCY:
051                String resKey1 = RequestUtil.getIpAddress(inv.getController().getRequest()) + ":" + resource;
052                doInterceptForConcurrency(limitConfigBean.getRate(), resKey1, null, inv);
053                break;
054            case LimitType.TOKEN_BUCKET:
055                doInterceptForTokenBucket(limitConfigBean.getRate(), resource, null, inv);
056                break;
057            case LimitType.IP_TOKEN_BUCKET:
058                String resKey2 = RequestUtil.getIpAddress(inv.getController().getRequest()) + ":" + resource;
059                doInterceptForTokenBucket(limitConfigBean.getRate(), resKey2, null, inv);
060                break;
061        }
062    }
063
064
065}