我有一个微服务,它是在kotlin中实现的spring云网关。因此,作为功能的一部分,如果我在application.yaml中的过滤器配置中发现了特定的参数组合,则需要失败启动此服务。为了给出过滤器配置,我们使用内联表示法。例如:
spring:
cloud:
gateway:
routes:
- id: test1
predicates:
- Path=/test1/**
filters:
- RewritePath=/test1/(?<segment>.*), /${segment}
- TLS= OPTIONAL, NONE, TEST
- id: test2
predicates:
- Path=/test2/**
filters:
- RewritePath=/test2/(?<segment>.*), /${segment}
- TLS= MANDATORY, NONE, TEST
在这个示例配置中,TLS过滤器的ags组合为MANDATORY + NONE,那么在这种情况下,该服务应该在开始时失败,因为">MANDATORY + NONE不是正确的组合">
有什么建议吗??
实现此目的的一种方法是创建ApplicationEventListener。基本上,您将注册其中一个侦听器来侦听Spring引导事件:(其中之一:https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/event/package-summary.html)
您可以在这里看到一个示例实现:https://stackoverflow.com/questions/56372260/spring-load-application-properties-in-application-listener
。在这个示例中,正在加载属性。在您的情况下,我认为您可以检查您感兴趣的属性,并在任何违反您的要求时抛出RuntimeException。
我在kotlin中找到了另一种方法。在类中使用init块。https://blog.mindorks.com/understanding-init-block-in-kotlin
TLSFilter代码,如果在该过滤器的路由中发现特定的组合将失败
class TLSFilter(
private val filterProperties: TLSFilterProperties,) : GatewayFilter {
private val logger = logger()
init {
if (filterProperties.mode == DISABLE && (filterProperties.type?.isNotEmpty() == true)) {
throw IllegalStateException("Security mode `DISABLE` should not be present with any security type in filter configuration.")
}
if ((filterProperties.mode == MANDATORY || filterProperties.mode == OPTIONAL) && filterProperties.type?.equals(NONE.name) == true) {
throw IllegalStateException("Security mode = ${filterProperties.mode} with security type = NONE is not a valid configuration.")
}
}}
TLSFilterProperties类,它自动绑定到应用程序。spring云网关应用的Yml文件。
/**
* Properties that should be initialized in filter configuration properties
*/
class TLSFilterProperties {
lateinit var mode: SecurityMode
var type: String? = null
var alias: String? = null
companion object {
val configFieldsOrder = listOf(
"mode",
"type",
"alias"
)
}
}