java实现graphql接口调用

在项目中引用graphql client
目前这个graphql client只支持post的graphql server

使用maven构建依赖关系

<dependency>
    <groupId>org.mountcloud</groupId>
    <artifactId>graphql-client</artifactId>
    <version>1.1</version>
</dependency>
 

用例
QUERY
构建graphql client

//graphql服务器地址
String serverUrl = "http://localhost:8080/graphql";
//build一个新的graphqlclient
GraphqlClient graphqlClient = GraphqlClient.buildGraphqlClient(serverUrl);
 
//如果说graphql需要健全信息我们可以用map来进行传递
Map<String,String> httpHeaders = new HashMap<>();
httpHeaders.put("token","graphqltesttoken");
//设置http请求的头
graphqlClient.setHttpHeaders(httpHeaders);
发起一个简单的query查询

//创建一个Query并设置query的名字为findUser
//如果有特殊需要可以自己继承GraphqlQuery,DefaultGraphqlQuery已经可以满足所有请求了
GraphqlQuery query = new DefaultGraphqlQuery("findUser");
 
//我们需要查询user的名字,性别还有年龄,设置需要查询的这三个属性。
query.addResultAttributes("name","sex","age");
 
try {
    //执行query
    GraphqlResponse response = graphqlClient.doQuery(query);
    //获取数据,数据为map类型
    Map result = response.getData();
} catch (IOException e) {
    e.printStackTrace();
}
对应的graphql语句为:

query{
    findUser{
        name
        sex
        age
    }
}

设置复杂的查询结果

//创建一个Query并设置query的名字为findUser
//如果有特殊需要可以自己继承GraphqlQuery,DefaultGraphqlQuery已经可以满足所有请求了
GraphqlQuery query = new DefaultGraphqlQuery("findUser");
 
//------------------------------------------------------------------------
//查询名字为张三,年龄为23岁的人,这里的参数类型一定要与query的参数类型一致
query.addParameter("name","张三").addParameter("age",23);
 
//------------------------------------------------------------------------
//我们需要查询user的名字,性别还有年龄,设置需要查询的这三个属性。
query.addResultAttributes("name","sex","age");
 
//------------------------------------------------------------------------
//查询用户的部门
ResultAttributtes departmentAttr = new ResultAttributtes("department");
//查询部门的名字和编号
departmentAttr.addResultAttributes("name","code");
 
//查询部门所属的公司
ResultAttributtes companyAttr = new ResultAttributtes("company");
//查询部门所属公司的名字
companyAttr.addResultAttributes("name");
 
//将部门和公司两者关联起来
departmentAttr.addResultAttributes(companyAttr);
 
//将需要查询的这个语句放到query里
query.addResultAttributes(departmentAttr);
 
//------------------------------------------------------------------------
try {
    //执行query
    GraphqlResponse response = graphqlClient.doQuery(query);
    //获取数据,数据为map类型
    Map result = response.getData();
} catch (IOException e) {
    e.printStackTrace();
}
对应的graphql语句为:

query{
    findUser(name:"张三",age:23){
        name
        sex
        age
        department{
            name
            code
            company{
                name
            }
        }
    }
}

MUTATION
这里只写一个复杂的mutaion,其实跟query一样

//创建一个mutation并设置名字为updateUser
GraphqlMutation mutation = new DefaultGraphqlMutation("updateUser");
 
//设置参数,用户id为12,名字为张三,年龄为24
mutation.addParameter("id",12).addParameter("name","张三").addParameter("age",24);
 
//获取修改的结果
mutation.addResultAttributes("code");
 
//获取结果里的数据:data对象昂
ResultAttributtes dataAttr = new ResultAttributtes("data");
//获取data里的消息、修改执行状态与时间戳
dataAttr.addResultAttributes("message","state","date");
 
//将data与mutation关联起来
mutation.addResultAttributes(dataAttr);
 
//执行mutation
try {
    GraphqlResponse mutationResponse = graphqlClient.doMutation(mutation);
    //同样返回的数据也是map的
    Map mutationResult = mutationResponse.getData();
} catch (IOException e) {
    e.printStackTrace();
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
假设我们有一个GraphQL接口,在其中定义了一个查询类型`query`,并且有一个名为`getUser`的查询字段,用于查询用户的详细信息。 下面是Java代码示例,用于调用GraphQL接口并查询用户信息: ```java import graphql.GraphQL; import graphql.schema.DataFetchingEnvironment; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLSchema; import graphql.schema.StaticDataFetcher; import graphql.schema.idl.RuntimeWiring; import graphql.schema.idl.SchemaGenerator; import graphql.schema.idl.SchemaParser; import graphql.schema.idl.TypeDefinitionRegistry; import java.io.File; import java.io.IOException; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; public class GraphQLClient { public static void main(String[] args) throws IOException { // 读取GraphQL schema定义 File schemaFile = new File("schema.graphqls"); String schemaString = FileUtils.readFileToString(schemaFile, "UTF-8"); // 创建GraphQL schema解析器 SchemaParser schemaParser = new SchemaParser(); TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schemaString); // 创建运行时绑定 RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring() .type("Query", builder -> builder .dataFetcher("getUser", new StaticDataFetcher(Map.of( "id", 1, "name", "Alice", "email", "[email protected]" ))) ) .build(); // 创建GraphQL schema生成器 SchemaGenerator schemaGenerator = new SchemaGenerator(); GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring); // 创建GraphQL实例 GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build(); // 定义查询语句 String query = "{ getUser { id name email } }"; // 执行查询 Map<String, Object> result = graphQL.execute(query).getData(); // 输出结果 ObjectMapper objectMapper = new ObjectMapper(); System.out.println(objectMapper.writeValueAsString(result)); } } ``` 在上面的代码中,我们首先读取GraphQL schema定义文件并解析它,然后创建运行时绑定以定义查询字段的数据抓取器。 接下来,我们使用GraphQL schema生成器创建实际的GraphQL schema,并使用它创建一个GraphQL实例来执行查询。 最后,我们定义查询语句,执行查询,并输出结果。在这个示例中,我们只查询了一个用户,但是你可以根据你的需要修改查询语句和数据抓取器来查询更多的信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值