使用Kotlin+Spring Boot时Apollo Client抛出网络异常求助
问题分析与解决方案
你的代码存在几个关键问题,结合网络错误提示,以下是具体的排查和修复步骤:
1. Controller层协程使用错误
getApolloData是普通同步方法,但内部手动启动协程执行异步逻辑,会导致:
- 协程在后台独立执行,方法本身无法将协程的返回结果传递给Spring MVC,请求会因等待不到返回值超时或返回空
- 真实的网络错误细节被掩盖
修复后的Controller代码:
@RestController class ControllerExample(private val serviceExample: ServiceExample) { private val logger = LoggerFactory.getLogger(this.javaClass) @GetMapping("/apollo") suspend fun getApolloData(): ApolloResponse<MemberQuery.Data> { return try { val response = serviceExample.getMemberData() logger.info("response $response") response } catch (ex: Exception) { logger.error("获取Apollo数据失败", ex) throw ex } } }
- 将方法改为
suspend函数,利用Spring对Kotlin协程的原生支持,无需手动创建CoroutineScope - 直接在方法内调用挂起函数,确保请求能正确获取返回结果
2. Service层ApolloClient重复创建
每次调用getMemberData都新建ApolloClient实例,既浪费资源,还可能导致连接池管理混乱,增加网络请求失败概率。
修复方案:将ApolloClient配置为单例Bean
首先创建配置类:
@Configuration class ApolloConfig { @Bean fun apolloClient(): ApolloClient { return ApolloClient.Builder() .serverUrl("https://your-real-graphql-url") // 替换为真实可访问的GraphQL地址 .addHttpHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE) .build() } }
然后修改Service类注入ApolloClient:
@Service class ServiceExample(private val apolloClient: ApolloClient) { private val logger = LoggerFactory.getLogger(this.javaClass) suspend fun getMemberData(): ApolloResponse<MemberQuery.Data> { return try { val response = apolloClient.query(MemberQuery()).execute() logger.info("response >>>> ${response}") response } catch (ex: ApolloException) { logger.error("获取会员数据失败", ex) throw ex } } }
3. 网络错误排查步骤
结合Failed to execute GraphQL http network错误,还需做以下检查:
- 验证GraphQL服务地址:用Postman、curl等工具测试
serverUrl是否能正常访问,排查是否存在代理、防火墙、SSL证书问题 - 完善依赖配置:确保项目引入了必要的Apollo和Spring协程依赖(以Gradle为例):
implementation("com.apollographql.apollo3:apollo-runtime:3.8.2") implementation("com.apollographql.apollo3:apollo-coroutines-support:3.8.2") implementation("org.springframework.boot:spring-boot-starter-webflux") // 或Spring 6+的spring-boot-starter-web
- 打印完整异常栈:在catch块中使用
logger.error("错误信息", ex),而非仅打印localizedMessage,以便查看具体错误原因(如连接超时、404/500状态码等) - 确认Spring版本支持:确保使用Spring Boot 2.6+版本,以支持Kotlin协程的Web请求处理
内容的提问来源于stack exchange,提问作者Sami
相关产品推荐
相关产品推荐

