新年開箱 | 火爆外網(wǎng)的 DGS 框架上手

Netflix 已開放其 Domain Graph Service(DGS)框架的源代碼 ,該框架是為了方便整合 GraphQL 使用,用于簡化 GraphQL 的實(shí)現(xiàn)。

GraphQL 主要是作用于數(shù)據(jù)接口,比如前端后端交互。無需定義或修改后臺 Controller、Service 等業(yè)務(wù)代碼即可實(shí)現(xiàn)靈活的數(shù)據(jù)變更,客戶端可以自由獲取服務(wù)端事先定義好的數(shù)據(jù),提高了交互接口的靈活性
組件依賴
- graphql-dgs-spring-boot-starter
<dependency>
????<groupId>com.netflix.graphql.dgsgroupId>
????<artifactId>graphql-dgs-spring-boot-starterartifactId>
????<version>3.5.1version>
dependency>
- DGS 必須從 jcenter 下載,不然部分依賴無法下載。踩坑很久
?<profiles>
??<profile>
???<activation>
????<activeByDefault>trueactiveByDefault>
???activation>
???<repositories>
????<repository>
?????<snapshots>
??????<enabled>falseenabled>
?????snapshots>
?????<id>centralid>
?????<name>bintrayname>
?????<url>https://jcenter.bintray.comurl>
????repository>
???repositories>
???<pluginRepositories>
????<pluginRepository>
?????<snapshots>
??????<enabled>falseenabled>
?????snapshots>
?????<id>centralid>
?????<name>bintray-pluginsname>
?????<url>https://jcenter.bintray.comurl>
????pluginRepository>
???pluginRepositories>
???<id>bintrayid>
??profile>
?profiles>
定義接口 schema
- /src/main/resources/schema/schema.graphqls
此文件定義了客戶端請求入?yún)⒏袷胶筒樵償?shù)據(jù)類型
type?Query?{
????shows(title:?String?,releaseYear:?Int):?[Show]
}
type?Show?{
????title:?String
????releaseYear:?Int
}
定義數(shù)據(jù)抽取規(guī)則
@DgsComponent
public?class?ShowsDatafetcher?{
?@DgsData(parentType?=?"Query",?field?=?"shows")
?public?List?shows(@InputArgument("title")?String?title,?@InputArgument("releaseYear")?Integer?releaseYear)? {
??if?(title?==?null)?{
???return?shows;
??}
??return?shows.stream().filter(s?->?s.getTitle().contains(title)).collect(Collectors.toList());
?}
????//?模擬?DB?查詢
???private?final?List?shows?=?List.of(
???new?Show("java",?1995),
???new?Show("php",?1995),
???new?Show("python",?1990),
???new?Show("golang",?2009),
???new?Show("rust",?2015)
?);
}
UI 前端調(diào)試
- 訪問: http://localhost:8080/graphiql

- 條件查詢

接口調(diào)用
curl?--location?--request?POST?'http://localhost:8080/graphql'?\
--header?'Content-Type:?application/json'?\
--data-raw?'{"query":"{\n??shows(title:?\"java\",?releaseYear:?1995)?{\n????title\n????releaseYear\n??}\n}\n","variables":null}'
java 調(diào)用
@SpringBootTest(classes?=?{DgsAutoConfiguration.class,?ShowsDatafetcher.class})
class?ShowsDatafetcherTests?{
?@Autowired
?DgsQueryExecutor?dgsQueryExecutor;
?@Test
?void?shows()?{
??List?titles?=?dgsQueryExecutor.executeAndExtractJsonPath(
????"?{?shows?{?title?releaseYear?}}",
????"data.shows[*].title");
??assertThat(titles).contains("java");
?}
}
本節(jié)源碼
源碼: https://github.com/lltx/dgs-demo
DGS 官網(wǎng): https://netflix.github.io/dgs
往期推薦
新年開箱 | Spring Authorization Server 全新的授權(quán)服務(wù)器上手
5分鐘擁抱云原生 | SpringBoot 遷移至 Quarkus
評論
圖片
表情
