You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解读Ballerina GraphQL服务的Query、Mutation、Subscription及Schema定义

Ballerina GraphQL 操作解读与Schema定义指南

一、三类核心操作的作用解读

在Ballerina的GraphQL服务中,Query、Mutation、Subscription分别对应数据交互的三类核心场景:

  • Query:只读的数据查询入口,用于获取后端数据,不会改变服务端状态。比如示例SDL里的greeting字段,对应Ballerina中返回问候文本的查询函数。
  • Mutation:数据修改操作入口,负责执行创建、更新、删除等会改变服务端状态的操作。比如示例中的setName,对应Ballerina里修改存储名称并返回结果的函数。
  • Subscription:实时数据推送通道,通过持久连接向客户端推送服务端的实时更新。比如示例里的greetings,对应Ballerina中返回数据流的函数,实现消息的实时推送。

二、Ballerina 中 Schema 的定义方式及类型位置

Ballerina不依赖SDL手动编写Schema,而是通过语言原生的服务结构+注解来定义,所有操作类型都封装在GraphQL服务内部:

1. 基础服务结构

首先定义一个带有@graphql:Service注解的HTTP服务,这是GraphQL Schema的载体,所有Query、Mutation、Subscription操作都定义在这个服务类中:

import ballerina/graphql;
import ballerina/http;

service /graphql on new http:Listener(9090) {
    // 各类操作函数写在这里
}

2. Query 类型的定义

服务中的公共无注解函数会自动被识别为Query类型的字段,无需额外标记:

service /graphql on new http:Listener(9090) {
    // 对应SDL中的 Query.greeting: String!
    public function greeting() returns string {
        return "Hello, Guest!";
    }
}

3. Mutation 类型的定义

给公共函数加上@graphql:Mutation注解,该函数就会被归类到Mutation类型下:

service /graphql on new http:Listener(9090) {
    private string userName = "Guest";

    // 对应SDL中的 Mutation.setName(name: String!): String!
    @graphql:Mutation
    public function setName(string name) returns string {
        self.userName = name;
        return "Successfully set name to: " + name;
    }
}

4. Subscription 类型的定义

给返回stream类型的公共函数加上@graphql:Subscription注解,即可实现订阅功能:

import ballerina/time;

service /graphql on new http:Listener(9090) {
    // 对应SDL中的 Subscription.greetings: String!
    @graphql:Subscription
    public stream<string, error?> greetings() returns stream<string, error?> {
        // 模拟每秒推送一次实时问候
        return stream {
            int count = 0;
            while count < 10 {
                count += 1;
                check wait 1000;
                yield "Real-time greeting at " + time:format(time:utcNow(), "HH:mm:ss");
            }
        };
    }
}

5. 自动生成SDL

Ballerina会根据服务中的函数定义自动生成对应的SDL Schema,你可以通过访问GraphQL Playground(默认路径http://localhost:9090/graphql)查看生成的完整Schema,无需手动编写SDL。如果需要自定义Schema,也可以通过@graphql:Schema注解指定SDL内容,但大多数场景下自动生成即可满足需求。

内容的提问来源于stack exchange,提问作者Dimuthu Madushan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 19:01:20