All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.apzda.cloud.adapter.spring.SentinelWebInterceptor Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 1999-2019 Alibaba Group Holding Ltd.
 *
 * Licensed 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
 *
 *      https://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 com.apzda.cloud.adapter.spring;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.apzda.cloud.adapter.spring.callback.UrlCleaner;
import com.apzda.cloud.adapter.spring.config.SentinelWebMvcConfig;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;

import java.util.Objects;

/**
 * Spring Web MVC interceptor that integrates with Sentinel.
 *
 * @author kaizi2009
 * @since 1.7.1
 */
public class SentinelWebInterceptor extends AbstractSentinelInterceptor {

    private final SentinelWebMvcConfig config;

    public SentinelWebInterceptor() {
        this(new SentinelWebMvcConfig());
    }

    public SentinelWebInterceptor(SentinelWebMvcConfig config) {
        super(config);
        // Use the default config by default.
        this.config = Objects.requireNonNullElseGet(config, SentinelWebMvcConfig::new);
    }

    @Override
    protected String getResourceName(HttpServletRequest request) {
        // Resolve the Spring Web URL pattern from the request attribute.
        Object resourceNameObject = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        if (!(resourceNameObject instanceof String resourceName)) {
            return null;
        }
        UrlCleaner urlCleaner = config.getUrlCleaner();
        if (urlCleaner != null) {
            resourceName = urlCleaner.clean(resourceName);
        }
        // Add method specification if necessary
        if (StringUtil.isNotEmpty(resourceName) && config.isHttpMethodSpecify()) {
            resourceName = request.getMethod().toUpperCase() + ":" + resourceName;
        }
        return resourceName;
    }

    @Override
    protected String getContextName(HttpServletRequest request) {
        if (config.isWebContextUnify()) {
            return super.getContextName(request);
        }

        return getResourceName(request);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy