Kotlin实战之获取本地配置文件、远程Apollo配置失败问题排查

背景

Kotlin作为一门JVM脚本语言,收到很多Java开发者的青睐。

项目采用Java+Kotlin混合编程。Spring Boot应用开发,不会发生变动的配置放在本地配置文件,可能会变化的配置放在远程Apollo Server。

问题

因为业务需要,需要增加一个可能会持续更新的配置,然后通过if else逻辑来加以判断。

apollo配置:
在这里插入图片描述
下面截图里的硬编码是未解决问题的 back-up 方案:
在这里插入图片描述
控制台打印:
在这里插入图片描述
事实上,本地开发时,习惯性先实现业务逻辑,一开始并没有在Apollo新增配置screen.channel,而是采用上面图2里的硬编码方式:

@Value("\${screen.channel: xhwjk_screen}")
var screenChannel: String? = null

这种方式不会去读取本地配置文件,也不会读取Apollo Server的配置,直接设置一个default值,也就是xhwjk_screen,但断点调试时,拿不到数据。

在本地bootstrap.yml文件里新增配置:

screen:
  channel: xhwjk_screen,pdwjk_screen

另外application.yml里也试过增加相同的配置项。

结论都是:获取不到配置。

对比

相同的配置,放在一个Java Controller里面就没有问题:

@Slf4j
@RestController
@RequestMapping("/dialog")
public class AuthenticationCheckController {
    
    
    @Value("${screen.channel: xhwjk_screen}")
    private String screenChannel;

    @GetMapping(value = "/authentication")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void checkAuthentication() {
    
    
        LOGGER.info("ff:{}", screenChannel);
        // This resource just returns a 204 No Content in case the request is authenticated.
    }
}

控制台打印:

AuthenticationCheckController | checkAuthentication | 28 | - ff:xhwjk_screen,pdwjk_screen

注:
JDK版本:OpenJDK-11
Spring Boot版本:2.1.6.RELEASE
Spring Cloud版本:Greenwich.RELEASE
Kotlin版本:1.3.72

扫描二维码关注公众号,回复: 16886215 查看本文章

排查

尝试1

带着上面描述的问题现象搜索,找到stackoverflow-how-to-get-value-from-application-yml-in-springboot

Apollo新增一个配置:
在这里插入图片描述
新增一个配置DialogConfig.kt类:

@Component
@ConfigurationProperties("dialog")
class DialogConfig {
    
    
    var screenChannel: String? = null
}

引用此配置:

@Resource
private val dialogConfig: DialogConfig? = null

仍然拿不到配置:
在这里插入图片描述

尝试2

找到另一篇stackoverflow-how-to-get-variable-from-spring-application-yaml-in-kotlin)
还是上面的DialogConfig.kt,引用配置:

@Resource
lateinit var dialogConfig: DialogConfig

直接报错:
kotlin.UninitializedPropertyAccessException: lateinit property dialogConfig has not been initialized
在这里插入图片描述
参考:stackoverflow-uninitializedpropertyaccessexception,使用前判断一下,没有判断的必要,还是拿不到数据。

尝试3

DialogConfig变成Java类:

@Component
@ConfigurationProperties("dialog")
public class DialogConfig {
    
    
    public String screenChannel;
}

引用此配置:

@Resource
var dialogConfig: DialogConfig? = null

还是不行!
在这里插入图片描述

解决

实在没办法,硬编码解决问题,参考截图一。

吐了。。

秃了。

猜你喜欢

转载自blog.csdn.net/lonelymanontheway/article/details/132305665