springboot整合graphql
GraphQL是比REST更高效、强大和灵活的新一代API标准。详细的可以看官网GraphQL。
下面介绍一个Spring boot整合graphql简单的例子。
项目准备:相关依赖的引入:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25<dependencies>
<!--web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--graphql -->
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>11.0.0</version>
</dependency>
<!--playground -->
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>playground-spring-boot-starter</artifactId>
<version>11.0.0</version>
</dependency>
</dependencies>
Query
定义schema,分别为:
query.graphqls
1
2
3type Query{
billingAccount(id: ID): BillingAccount
}billingAccount.graphqls
1
2
3
4
5type BillingAccount {
id: ID!
name: String!
currency: Currency
}currency.graphqls
1
2
3
4enum Currency{
RMB,
USD
}定义基础要操作的模型
1
2
3
4
5
6
7@Builder
@Value
public class BillingAccount {
UUID id;
String name;
Currency currency;
}1
2
3public enum Currency {
RMB, USD
}定义resolver
1
2
3
4
5
6
7
8
9
10
11
12@Slf4j
@Component
public class BillingAccountResolver implements GraphQLQueryResolver {
public BillingAccount billingAccount(UUID id){
log.info("receive billingAccount id is: "+ id);
return BillingAccount.builder()
.id(id)
.currency(Currency.RMB)
.name("张三")
.build();
}
}效果图
mutation
- 定义schema
1 |
|
- 定义input
1 |
|
- 定义input 对应的model
1 |
|
- 定义mutationResolver
1 |
|
效果图
!
springboot整合graphql
http://example.com/springboot整合graphql/