Spring Boot GraphQL订阅请求返回405 METHOD_NOT_ALLOWED问题排查
Spring Boot GraphQL订阅返回405 METHOD_NOT_ALLOWED问题排查
问题分析
从日志来看,核心问题是GET请求/graphql被返回405,同时伴随Tomcat的EOFException(这是WebSocket握手失败后客户端断开连接导致的连锁错误)。GraphQL订阅依赖WebSocket协议,普通HTTP GET请求无法处理订阅逻辑,需从端点配置、权限拦截、依赖完整性三个方向排查。
解决方案
1. 修正客户端订阅的协议与端点
GraphQL订阅必须通过WebSocket协议发起连接,而非普通HTTP请求:
- Spring GraphQL默认订阅端点为
/graphql,但客户端需使用ws://或wss://协议连接,例如ws://localhost:8000/graphql;若误用HTTP GET请求该地址(普通GraphQL接口仅支持POST),必然返回405。
2. 调整Spring Security拦截规则
日志显示Spring Security正在拦截GET /graphql请求,需允许WebSocket握手请求通过:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { return http .authorizeHttpRequests(auth -> auth .requestMatchers("/graphql").permitAll() .anyRequest().authenticated() ) .csrf(csrf -> csrf.ignoringRequestMatchers("/graphql")) .build(); }
3. 补充WebSocket依赖
除graphql-spring-boot-starter外,必须引入WebSocket Starter以支持订阅功能:
<!-- Maven --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
// Gradle implementation 'org.springframework.boot:spring-boot-starter-websocket'
4. 启用GraphQL WebSocket支持
确保项目中配置了WebSocket启用类:
@Configuration @EnableWebSocketGraphQl public class GraphQlWebSocketConfig { }
验证步骤
- 重启服务后,用WebSocket客户端(如wscat)测试连接:
wscat -c ws://localhost:8000/graphql
- 连接成功后发送订阅请求 payload,确认是否能正常接收推送。
内容的提问来源于stack exchange,提问作者robel pop
相关产品推荐
相关产品推荐

