Spring Cloud Config Server连接远程Git失败,报字符串索引越界异常
我遇到过类似的问题,结合你提供的信息——远程Git仓库(GitHub)访问抛出StringIndexOutOfBoundsException: String index out of range: -1,但本地Git仓库完全正常,再加上你使用的版本,这个问题基本是旧版本Spring Cloud Config的已知bug,或者版本不兼容导致的,给你几个可行的解决方案:
一、检查Spring Boot和Spring Cloud的版本兼容性
Spring Boot 2.0.2.RELEASE对应的Spring Cloud版本应该是Finchley.SR2(或者同系列的更高版本),如果你的项目没正确引入Spring Cloud的依赖管理,很容易出现版本不匹配的问题。
配置方式(Maven为例)
在pom.xml里添加依赖管理:
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.SR2</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
Gradle的话添加这段:
dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:Finchley.SR2" } }
二、调整Git URI的格式
虽然GitHub支持不带.git后缀的仓库访问,但旧版本的Config Server对这个可能比较敏感,试试给URI加上.git后缀:
spring: cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo.git server: port: 9999
三、清理本地Git缓存
Config Server会在本地缓存仓库内容,旧缓存可能引发异常。默认缓存目录是C:\Users\<你的用户名>\.spring-cloud\config-repo,手动删掉这个文件夹,再重启服务,让它重新克隆远程仓库。
四、指定自定义的本地缓存目录
Windows环境下默认路径偶尔会有解析问题,你可以显式指定一个本地目录来存储Git仓库:
spring: cloud: config: server: git: uri: https://github.com/spring-cloud-samples/config-repo.git basedir: D:/temp/config-cache # 用正斜杠或者双反斜杠 server: port: 9999
验证解决方案
做完上面的配置后重启服务,再访问http://localhost:9999/bar/default应该就能正常获取配置了。如果还是不行,建议升级到Spring Boot 2.0.9.RELEASE+Spring Cloud Finchley.SR4,这些版本修复了不少旧bug,稳定性更好。
内容的提问来源于stack exchange,提问作者Alessio Fiore

