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; } } |

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

相关推荐
xlsw_2 分钟前
java全栈day20--Web后端实战(Mybatis基础2)
java·开发语言·mybatis
神仙别闹1 小时前
基于java的改良版超级玛丽小游戏
java
Dream_Snowar1 小时前
速通Python 第三节
开发语言·python
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭1 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
暮湫2 小时前
泛型(2)
java
超爱吃士力架2 小时前
邀请逻辑
java·linux·后端
南宫生2 小时前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论
转码的小石2 小时前
12/21java基础
java
高山我梦口香糖2 小时前
[react]searchParams转普通对象
开发语言·前端·javascript
李小白662 小时前
Spring MVC(上)
java·spring·mvc