com.github.shepherdviolet.glacimon.spring.helper.sentinel.EzSentinelConfiguration Maven / Gradle / Ivy
/*
* Copyright (C) 2022-2022 S.Violet
*
* 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
*
* http://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.
*
* Project GitHub: https://github.com/shepherdviolet/glacimon
* Email: [email protected]
*/
package com.github.shepherdviolet.glacimon.spring.helper.sentinel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 注解方式启用JSON格式的Sentinel规则设置器. 说明文档见: https://github.com/shepherdviolet/glacimon/blob/master/docs/ezsentinel/guide.md
*
* 依赖: compile "com.google.code.gson:gson:$version_gson"
*
* @author shepherdviolet
*/
@Configuration
public class EzSentinelConfiguration {
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* 规则设置器
*/
@Bean("glacispring.helper.ezSentinelRuleConfigurer")
@ConditionalOnProperty(name = "spring.cloud.sentinel.enabled", matchIfMissing = true)
public EzSentinelRuleConfigurer ezSentinelRuleConfigurer(){
return new JsonEzSentinelRuleConfigurer();
}
/**
* 规则设置器绑定参数glacispring.helper.ez-sentinel.rule-data
*/
@Bean("glacispring.helper.ezSentinelRuleConfigurerPropertySetter")
@ConditionalOnProperty(name = "spring.cloud.sentinel.enabled", matchIfMissing = true)
public Object ezSentinelRuleConfigurerPropertySetter(AbstractEzSentinelRuleConfigurer ezSentinelRuleConfigurer){
return new Object() {
/**
* 监听本地配置和Apollo配置, 更新规则
*/
@Value("${glacispring.helper.ez-sentinel.rule-data:}")
public void setRuleData(String ruleData) {
ezSentinelRuleConfigurer.update(ruleData);
}
};
}
/**
* Sentinel开关
*/
@Value("${spring.cloud.sentinel.enabled:true}")
public void setEnabled(boolean enabled) {
//这个只对核心有效, 即对本地统计限流熔断有效
com.alibaba.csp.sentinel.Constants.ON = enabled;
logger.info("EzSentinel | Sentinel " + (enabled ? "Enabled" : "Disabled"));
}
}