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

com.alibaba.csp.ahas.sentinel.gateway.zuul.ZuulEnvironmentPostProcessor Maven / Gradle / Ivy

There is a newer version: 1.6.8-safe-jdk8
Show newest version
package com.alibaba.csp.ahas.sentinel.gateway.zuul;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * 判断Zuul网关下失效掉web插件,防止访问路径错误情况下抓出url接口
 * @author guanyu
 */
public class ZuulEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private final static String SENTINEL_SPRING_WEB_ENABLED = "spring.cloud.ahas.sentinel.web.enabled";

    private final static String PROPERTY_SOURCE_NAME = "defaultProperties";

    @Value("${spring.cloud.ahas.sentinel.zuul.environment.enabled:true}")
    private boolean setZuulEnvironment;

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        if(setZuulEnvironment) {
            addDefaultPropertySource(environment);
        }
    }

    private void addDefaultPropertySource(ConfigurableEnvironment environment) {

        Map map = new HashMap();

        configureDefaultProperties(map);

        addOrReplace(environment.getPropertySources(), map);
    }

    private void configureDefaultProperties(Map source) {
        // Required Properties
        source.put(SENTINEL_SPRING_WEB_ENABLED, "false");
    }

    private void addOrReplace(MutablePropertySources propertySources,
                              Map map) {
        MapPropertySource target = null;
        if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
            PropertySource source = propertySources.get(PROPERTY_SOURCE_NAME);
            if (source instanceof MapPropertySource) {
                target = (MapPropertySource) source;
                for (String key : map.keySet()) {
                    if (!target.containsProperty(key)) {
                        target.getSource().put(key, map.get(key));
                    }
                }
            }
        }
        if (target == null) {
            target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
        }
        if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
            propertySources.addLast(target);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy