簡體   English   中英

不綁定 ==> Consul KV + Kotlin Spring 引導 @ConfigurationProperties @ConstructorBinding

[英]Not Binding ==> Consul KV + Kotlin Spring Boot @ConfigurationProperties @ConstructorBinding

我需要將我們的 application.yml 配置移動到 Hashicorp 的 Consul。 我創建了一個簡單的 Spring 引導應用程序來完成所需的更改。 它將配置數據從 application.yml 加載到強類型 class。

但是,在注釋掉 application.yml 文件並在 bootstrap.yml 文件中啟用 consul 后,當我嘗試訪問 Consul KV 中的相同配置時,它在我的系統上作為 Docker 映像運行,配置數據始終為 null . 我一定錯過了一些簡單的東西,但我完全不知道它是什么。 以下是相關信息。

////////////////////////////////////////
// MyConsulApplication.kt
////////////////////////////////////////
@SpringBootApplication(scanBasePackages = ["com.example.myconsul"])
class MyConsulApplication

fun main(args: Array<String>) {
    runApplication<MyConsulApplication>(*args)
}
////////////////////////////////////////
// application.yml
////////////////////////////////////////
#myconsul:
#  message: howdy
////////////////////////////////////////
// bootstrap.yml
////////////////////////////////////////
server:
  port: 8080

spring:
  application:
    name: myconsul
  profiles:
    active: default
  cloud:
    consul:
      host: localhost
      port: 8500
      config:
        enabled: true  # Set to false to use the local application.yml file rather than the Consul configuration server.
        prefix: config
        defaultContext: application
      discovery:
        enabled: true
        instanceId: ${spring.application.name}:${random.value}
        healthCheckPath: /
        healthCheckInterval: 30s
////////////////////////////////////////
// AppProperties.kt
////////////////////////////////////////
@ConstructorBinding
//@RefreshScope
//@Scope("singleton")  // This is the default, but I wanted to be explicit about it.
@EnableConfigurationProperties(AppProperties::class)
@ConfigurationProperties("myconsul")
data class AppProperties(val message: String?) {

    @PostConstruct
    fun postConstruct() {
        println("====> $message")
    }
}
////////////////////////////////////////
// Consul KT Export
////////////////////////////////////////
[
    {
        "key": "config/myconsul/message",
        "flags": 0,
        "value": "SGFwcHkgSGFsbG93ZWVuIQ=="
    }
]
////////////////////////////////////////
// build.gradle.kts Dependencies
////////////////////////////////////////
extra["springCloudVersion"] = "Hoxton.BUILD-SNAPSHOT"

dependencies {
    // kapt dependencies required for IntelliJ auto complete of kotlin config properties class
    kapt("org.springframework.boot:spring-boot-configuration-processor")
    annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
    implementation("org.springframework.cloud:spring-cloud-starter-consul-config")
    implementation("org.springframework.cloud:spring-cloud-starter-consul-discovery")

    implementation("org.springframework.boot:spring-boot-starter-actuator")
    implementation("org.springframework.boot:spring-boot-starter-webflux")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
}
////////////////////////////////////////
// Console Logging of Launch
////////////////////////////////////////

2019-11-02 22:49:04.510  INFO 5401 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.retry.annotation.RetryConfiguration' of type [org.springframework.retry.annotation.RetryConfiguration$$EnhancerBySpringCGLIB$$1d6cbd94] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-11-02 22:49:04.519  INFO 5401 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$43c3286c] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

 :: Spring Boot ::  (v2.2.1.BUILD-SNAPSHOT)

2019-11-02 22:49:05.521  INFO 5401 --- [           main] b.c.PropertySourceBootstrapConfiguration : Located property source: CompositePropertySource {name='consul', propertySources=[ConsulPropertySource {name='config/myconsul,default/'}, ConsulPropertySource {name='config/myconsul/'}, ConsulPropertySource {name='config/application,default/'}, ConsulPropertySource {name='config/application/'}]}
2019-11-02 22:49:05.526  INFO 5401 --- [           main] c.e.myconsul.MyConsulApplicationKt       : The following profiles are active: default
2019-11-02 22:49:06.453  WARN 5401 --- [           main] o.s.boot.actuate.endpoint.EndpointId     : Endpoint ID 'bus-env' contains invalid characters, please migrate to a valid format.
2019-11-02 22:49:06.658  WARN 5401 --- [           main] o.s.boot.actuate.endpoint.EndpointId     : Endpoint ID 'bus-refresh' contains invalid characters, please migrate to a valid format.
2019-11-02 22:49:06.745  WARN 5401 --- [           main] o.s.boot.actuate.endpoint.EndpointId     : Endpoint ID 'service-registry' contains invalid characters, please migrate to a valid format.
2019-11-02 22:49:06.901  INFO 5401 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=6becbf98-b3f5-3e17-8c2f-cd8e1a8f2d5d
2019-11-02 22:49:06.956  INFO 5401 --- [           main] faultConfiguringBeanFactoryPostProcessor : No bean named 'errorChannel' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.
2019-11-02 22:49:06.961  INFO 5401 --- [           main] faultConfiguringBeanFactoryPostProcessor : No bean named 'taskScheduler' has been explicitly defined. Therefore, a default ThreadPoolTaskScheduler will be created.
2019-11-02 22:49:06.965  INFO 5401 --- [           main] faultConfiguringBeanFactoryPostProcessor : No bean named 'integrationHeaderChannelRegistry' has been explicitly defined. Therefore, a default DefaultHeaderChannelRegistry will be created.
2019-11-02 22:49:07.006  INFO 5401 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.retry.annotation.RetryConfiguration' of type [org.springframework.retry.annotation.RetryConfiguration$$EnhancerBySpringCGLIB$$1d6cbd94] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-11-02 22:49:07.041  INFO 5401 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'integrationChannelResolver' of type [org.springframework.integration.support.channel.BeanFactoryChannelResolver] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-11-02 22:49:07.046  INFO 5401 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'integrationDisposableAutoCreatedBeans' of type [org.springframework.integration.config.annotation.Disposables] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-11-02 22:49:07.058  INFO 5401 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.integration.config.IntegrationManagementConfiguration' of type [org.springframework.integration.config.IntegrationManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-11-02 22:49:07.063  INFO 5401 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration$IntegrationJmxConfiguration' of type [org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration$IntegrationJmxConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-11-02 22:49:07.070  INFO 5401 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration' of type [org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-11-02 22:49:07.074  INFO 5401 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'mbeanServer' of type [com.sun.jmx.mbeanserver.JmxMBeanServer] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-11-02 22:49:07.090  INFO 5401 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$43c3286c] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-11-02 22:49:07.594  WARN 5401 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2019-11-02 22:49:07.594  INFO 5401 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2019-11-02 22:49:07.601  INFO 5401 --- [           main] c.netflix.config.DynamicPropertyFactory  : DynamicPropertyFactory is initialized with configuration sources: com.netflix.config.ConcurrentCompositeConfiguration@83b0d0f
2019-11-02 22:49:07.752  INFO 5401 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'taskScheduler'
2019-11-02 22:49:07.946  INFO 5401 --- [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
====> null
2019-11-02 22:49:08.105  WARN 5401 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2019-11-02 22:49:08.105  INFO 5401 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2019-11-02 22:49:08.287  INFO 5401 --- [           main] c.f.c.c.BeanFactoryAwareFunctionRegistry : Looking up function 'null' with acceptedOutputTypes: []
2019-11-02 22:49:08.474  WARN 5401 --- [           main] ockingLoadBalancerClientRibbonWarnLogger : You already have RibbonLoadBalancerClient on your classpath. It will be used by default. As Spring Cloud Ribbon is in maintenance mode. We recommend switching to BlockingLoadBalancerClient instead. In order to use it, set the value of `spring.cloud.loadbalancer.ribbon.enabled` to `false` or remove spring-cloud-starter-netflix-ribbon from your project.
2019-11-02 22:49:08.507  WARN 5401 --- [           main] eactorLoadBalancerClientRibbonWarnLogger : You have RibbonLoadBalancerClient on your classpath. LoadBalancerExchangeFilterFunction that uses it under the hood will be used by default. Spring Cloud Ribbon is now in maintenance mode, so we suggest switching to ReactorLoadBalancerExchangeFilterFunction instead. In order to use it, set the value of `spring.cloud.loadbalancer.ribbon.enabled` to `false` or remove spring-cloud-starter-netflix-ribbon from your project.
2019-11-02 22:49:08.555  INFO 5401 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'configWatchTaskScheduler'
2019-11-02 22:49:08.565  INFO 5401 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'catalogWatchTaskScheduler'
2019-11-02 22:49:08.668  INFO 5401 --- [           main] o.s.c.s.m.DirectWithAttributesChannel    : Channel 'myconsul-1.springCloudBusInput' has 1 subscriber(s).
2019-11-02 22:49:08.777  INFO 5401 --- [           main] o.s.i.monitor.IntegrationMBeanExporter   : Registering MessageChannel springCloudBusInput
2019-11-02 22:49:08.860  INFO 5401 --- [           main] o.s.i.monitor.IntegrationMBeanExporter   : Registering MessageChannel errorChannel
2019-11-02 22:49:08.896  INFO 5401 --- [           main] o.s.i.monitor.IntegrationMBeanExporter   : Registering MessageChannel nullChannel
2019-11-02 22:49:08.910  INFO 5401 --- [           main] o.s.i.monitor.IntegrationMBeanExporter   : Registering MessageChannel springCloudBusOutput
2019-11-02 22:49:08.925  INFO 5401 --- [           main] o.s.i.monitor.IntegrationMBeanExporter   : Registering MessageHandler org.springframework.cloud.stream.binding.StreamListenerMessageHandler@7497a554
2019-11-02 22:49:08.973  INFO 5401 --- [           main] o.s.i.monitor.IntegrationMBeanExporter   : Registering MessageHandler errorLogger
2019-11-02 22:49:09.058  INFO 5401 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2019-11-02 22:49:09.058  INFO 5401 --- [           main] o.s.i.channel.PublishSubscribeChannel    : Channel 'myconsul-1.errorChannel' has 1 subscriber(s).
2019-11-02 22:49:09.058  INFO 5401 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started bean '_org.springframework.integration.errorLogger'
2019-11-02 22:49:09.121  INFO 5401 --- [           main] b.c.PropertySourceBootstrapConfiguration : Located property source: CompositePropertySource {name='consul', propertySources=[ConsulPropertySource {name='config/myconsul,default/'}, ConsulPropertySource {name='config/myconsul/'}, ConsulPropertySource {name='config/application,default/'}, ConsulPropertySource {name='config/application/'}]}
2019-11-02 22:49:09.157  INFO 5401 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : Adding {message-handler:outbound.springCloudBus} as a subscriber to the 'springCloudBusOutput' channel
2019-11-02 22:49:09.157  INFO 5401 --- [           main] o.s.c.s.m.DirectWithAttributesChannel    : Channel 'myconsul-1.springCloudBusOutput' has 1 subscriber(s).
2019-11-02 22:49:09.157  INFO 5401 --- [           main] o.s.i.endpoint.EventDrivenConsumer       : started bean 'outbound.springCloudBus'
2019-11-02 22:49:09.170  INFO 5401 --- [           main] o.s.c.c.b.ConsulInboundMessageProducer   : started org.springframework.cloud.consul.binder.ConsulInboundMessageProducer@878feb2
2019-11-02 22:49:09.339  INFO 5401 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8080
2019-11-02 22:49:09.375  INFO 5401 --- [           main] o.s.c.c.s.ConsulServiceRegistry          : Registering service with consul: NewService{id='myconsul-9d80f0a272c1126ed0ec586ee888be1f', name='myconsul', tags=[secure=false], address='192.168.0.11', meta=null, port=8080, enableTagOverride=null, check=Check{script='null', interval='30s', ttl='null', http='http://192.168.0.11:8080/', method='null', header={}, tcp='null', timeout='null', deregisterCriticalServiceAfter='null', tlsSkipVerify=null, status='null'}, checks=null}
2019-11-02 22:49:09.404  INFO 5401 --- [           main] c.e.myconsul.MyConsulApplicationKt       : Started MyConsulApplicationKt in 6.34 seconds (JVM running for 7.778)

AppProperties class 不是彈簧管理的 bean。 您需要將@EnableConfigurationProperties(AppProperties::class)添加到spring-managed bean:

@SpringBootApplication(scanBasePackages = ["com.example.myconsul"])
@EnableConfigurationProperties(AppProperties::class)
class MyConsulApplication

之后,您的屬性 class 將由 Spring 上下文管理。

如果您希望它使用@RefreshScope 可變且可刷新,則需要刪除@ConstructorBinding 並像這樣重寫您的AppProperties:

@ConstructorBinding
@RefreshScope
@ConfigurationProperties("myconsul")
class AppProperties {
    lateinit var message: String

    @PostConstruct
    fun postConstruct() {
        println("====> $message")
    }
}

因此,我通過創建 java 項目並讓它工作來解決這個問題。 接下來,基於我的 Java 項目,我創建了一個反應式 Kotlin 版本。 這兩個項目都可以正常工作並且是獨立的。 我希望他們可以幫助別人。 以下是項目的鏈接:

Java Consul鍵值示例

Kotlin 領事鍵值示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM