Java对接GraphQL

GraphQL的逻辑如果在java实现感觉还是很复杂,因为其相当于一种组排的策略模式。好在不需要进行相应的实现,只需要调用别人的接口即可。

但java调用GraphQL接口的成熟客户端好像就只有一个,当我们去maven中央仓库寻找客户端依赖时发现好像就只有这一个客户端

进入该依赖库发现GitHub地址:GitHub - graphql-java/graphql-java: GraphQL Java implementation

我们找到官方文档,可以看到结构确实复杂,学习成本很高。

所以没必要浪费太多时间。我随后找到了私人开源作品:

pom:

|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| <!-- https://mvnrepository.com/artifact/org.mountcloud/graphql-client --> <dependency> <groupId>org.mountcloud</groupId> <artifactId>graphql-client</artifactId> <version>1.2</version> </dependency> |

同理 我们去maven仓库寻找GitHub开源地址:GitHub - MountCloud/graphql-client: graphql client for java

发现给的例子很少但是简洁明了也符合我们需求。

所以,java对GraphQL的请求都模仿自这里,我直接把文档的内容搬过来然后做个对比:

复制代码
do query

|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| //crate client GraphqlClient client = GraphqlClient.buildGraphqlClient("http://localhost:8081/graphql"); //create http headers Map<String,String> headers = new HashMap<String,String>(); headers.put("token","123"); client.setHttpHeaders(headers); //create query GraphqlQuery query = new DefaultGraphqlQuery("findUsers"); //add query or mutation param query.addParameter("sex","man").addParameter("age",11); //add query response basics attribute query.addResultAttributes("id","name","age","sex"); //add query complex attributes ResultAttributtes classAttributte = new ResultAttributtes("class"); classAttributte.addResultAttributes("name","code"); //attributes can be more complex ResultAttributtes schoolAttributte = new ResultAttributtes("school"); schoolAttributte.addResultAttributes("name"); //class add school attribute classAttributte.addResultAttributes(schoolAttributte); //do query try { GraphqlResponse response = client.doQuery(query); //this map is graphql result Map data = response.getData(); } catch (IOException e) { e.printStackTrace(); } query is query{ findUsers(sex:"man",age:11){ id name age sex class{ name code school{ name } } } } |

复制代码
do mutation

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| //crate client GraphqlClient client = GraphqlClient.buildGraphqlClient("http://localhost:8081/graphql"); //create http headers Map<String,String> headers = new HashMap<String,String>(); headers.put("token","123"); client.setHttpHeaders(headers); //create mutaion GraphqlMutation mutation = new DefaultGraphqlMutation("updateUser"); //create param mutation.addParameter("id",1).addParameter("name","123").addParameter("age",18); //add more complex attribute to see do query demo //result mutation.addResultAttributes("code"); try { GraphqlResponse response = client.doMutation(mutation); //this map is graphql result Map data = response.getData(); } catch (IOException e) { e.printStackTrace(); } mutation is mutation{ updateUser(id:1,name:"123",age:18){ code } } |

复制代码
Complex structure request demo
复制代码
Mutation demo,The query is consistent with the mutation.

|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @Test public void testObjectParameter() throws IOException { String serverUrl = "http://localhost:8080/graphql"; GraphqlClient graphqlClient = GraphqlClient.buildGraphqlClient(serverUrl); Map<String,String> httpHeaders = new HashMap<>(); httpHeaders.put("token","graphqltesttoken"); graphqlClient.setHttpHeaders(httpHeaders); GraphqlMutation mutation = new DefaultGraphqlMutation("addUser"); List<User> users = new ArrayList<>(); users.add(new User("tim",SexEnum.M)); users.add(new User("sdf",SexEnum.F)); mutation.getRequestParameter().addParameter("classId","123").addObjectParameter("users",users); mutation.addResultAttributes("code"); System.out.println(mutation.toString()); } /** * test user */ class User{ public User(String name, SexEnum sexEnum) { this.name = name; this.sexEnum = sexEnum; } private String name; private SexEnum sexEnum; public String getName() { return name; } public void setName(String name) { this.name = name; } public SexEnum getSexEnum() { return sexEnum; } public void setSexEnum(SexEnum sexEnum) { this.sexEnum = sexEnum; } } /** * test user sex */ enum SexEnum{ M, F } |

复制代码
mutation is

|----------------------------------------------------------------------------------------------------------|
| mutation{ addUser(classId:"123",users:[{name:"tim",sexEnum:M},{name:"sdf",sexEnum:F}]){ code } } |

以上就是官方全部案例,即使你去百度得到的也不过是这些。

从案例中可以看出,请求有两种,一种是简单请求query,一种是复杂请求mutation。

要记住GraphQL的核心就是查询请求,无外乎封装条件。

所以GraphQL的查询请求很简单:

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @PostMapping("/find") // @RequestMapping(method = RequestMethod.POST, value = "/find") public Result find() { //1、graphql服务地址 String serverUrl = "https://api2.vetspire.com/graphql"; //2、build一个新的graphqlClient GraphqlClient graphqlClient = GraphqlClient.buildGraphqlClient(serverUrl); //3、使用Map来存储放入请求头,Authorization的密钥 Map<String, String> httpHeaders = new HashMap<>(); httpHeaders.put("Authorization", "SFMyNTY.g3QAAAACZAAEZGF0YW0AAAAIMTIxOjUxNDdkAAZzaWduZWRuBgA2HeSibwE.FSigojcmpREK5InTRp1iaxg_S2QQnz_Vd5_Z_PIlRQc"); //4、graphqlClient 设置http请求的头 graphqlClient.setHttpHeaders(httpHeaders); //下面开始发一个简单的query请求查询 //创建一个query并设置query的名字为org,如果有特殊的需求自己继承GraphqlQuery String queryMethodName = "org"; GraphqlQuery query = new DefaultGraphqlQuery(queryMethodName); // 如果需要增加一些必要的参数则使用query.addParameter(""): //设置需要查询的参数是id和name query.addResultAttributes("id", "name"); //通过上面的信息进行查询 GraphqlResponse response = null; try { response = graphqlClient.doQuery(query); } catch (IOException e) { e.printStackTrace(); } //获取数据,数据为map类型 Map result = response.getData(); System.out.println(result); System.out.println(result.get("data")); return new Result(true, StatusCode.SUCCESS.getCode(),result); } |

复杂一点的是更新的请求,需要组装条件模仿GraphQL的格式,还要封装相应的实体类:

|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @GetMapping("/updatePatient") public Result updatePatient() throws IOException { //1、graphql服务地址 String serverUrl = "https://api2.vetspire.com/graphql"; //2、build一个新的graphqlClient GraphqlClient graphqlClient = GraphqlClient.buildGraphqlClient(serverUrl); //3、使用Map来存储放入请求头,Authorization的密钥 Map<String, String> httpHeaders = new HashMap<>(); httpHeaders.put("Authorization", "SFMyNTY.g3QAAAACZAAEZGF0YW0AAAAIMTIxOjUxNDdkAAZzaWduZWRuBgA2HeSibwE.FSigojcmpREK5InTRp1iaxg_S2QQnz_Vd5_Z_PIlRQc"); //4、graphqlClient 设置http请求的头 graphqlClient.setHttpHeaders(httpHeaders); GraphqlMutation mutation = new DefaultGraphqlMutation("updatePatient"); //Patient patient = new Patient(24,"red"); Patient input = new Patient(24,"blue"); mutation.addParameter("id",847568).addObjectParameter("input",input); mutation.addResultAttributes("id","name","birthDate","color","species","clientId","updatedAt","insertedAt","breed"); //addObjectParameter("patient",patient); ResultAttributtes dataAttr = new ResultAttributtes("latestWeight"); mutation.addResultAttributes(dataAttr); GraphqlResponse mutationResponse = graphqlClient.doMutation(mutation); //同样返回的数据也是map的 Map result = mutationResponse.getData(); System.out.println(result); System.out.println(result.get("data")); return null; } class Patient{ public Integer getBirthDay() { return birthDay; } public void setBirthDay(Integer birthDay) { this.birthDay = birthDay; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } private Integer birthDay; private String color; private String breed; private String sex; public String getBreed() { return breed; } public void setBreed(String breed) { this.breed = breed; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getSpecies() { return species; } public void setSpecies(String species) { this.species = species; } private String species; public Patient(Integer birthDay,String color){ this.birthDay = birthDay; this.color = color; } } |

对比官网示例,步骤就清晰明了了。

相关推荐
KeithTsui6 分钟前
ZFC in LEAN 之 前集的等价关系(Equivalence on Pre-set)详解
开发语言·其他·算法·binder·swift
code .7 分钟前
C++各个版本的主要特性
开发语言·c++·现代c++
菜菜-plus7 分钟前
java设计模式之工厂模式
java·设计模式
哎呦没17 分钟前
健身行业创新:SpringBoot管理系统应用
java·spring boot·后端
暴怒香菜统治世界22 分钟前
数据结构--二叉树_链式(下)
c语言·开发语言·数据结构·算法·链表
烂漫心空24 分钟前
Spring Boot 整合 MyBatis
java·spring boot·maven·mybatis
SONGW201835 分钟前
其他节点使用kubectl访问集群,kubeconfig配置文件 详解
java·开发语言
Source.Liu1 小时前
【用Rust写CAD】第二章 第一节 Rust注释
开发语言·rust
许苑向上1 小时前
最详细【Elasticsearch】Elasticsearch Java API + Spring Boot集成 实战入门(基础篇)
java·数据库·spring boot·elasticsearch
柳叶寒1 小时前
医院信息化与智能化系统(17)
java·nacos·gateway·全栈·项目