新年开箱 | 火爆外网的 DGS 框架上手

JAVA架构日记

共 2126字,需浏览 5分钟

 ·

2021-02-22 18:23

f2a29a554a4f704ee69b17b06ce8c172.webp

Netflix 已开放其 Domain Graph Service(DGS)框架的源代码 ,该框架是为了方便整合 GraphQL 使用,用于简化 GraphQL 的实现。

5986675259d9b853e23ea2d4bcb25876.webp

GraphQL 主要是作用于数据接口,比如前端后端交互。无需定义或修改后台 Controller、Service 等业务代码即可实现灵活的数据变更,客户端可以自由获取服务端事先定义好的数据,提高了交互接口的灵活性

组件依赖

  • 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

此文件定义了客户端请求入参格式和查询数据类型

type Query {
    shows(title: String ,releaseYear: Int): [Show]
}

type Show {
    titleString
    releaseYear: Int
}

定义数据抽取规则

@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 前端调试

  • 访问: http://localhost:8080/graphiql
c06b63159a9678944f8c01c7089cfd73.webp
  • 条件查询
247dc2800ef79f29a2b8f259f71d5dae.webp

接口调用

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 调用

@SpringBootTest(classes = {DgsAutoConfiguration.classShowsDatafetcher.class})
class ShowsDatafetcherTests 
{

 @Autowired
 DgsQueryExecutor dgsQueryExecutor;

 @Test
 void shows() {
  List titles = dgsQueryExecutor.executeAndExtractJsonPath(
    " { shows { title releaseYear }}",
    "data.shows[*].title");
  assertThat(titles).contains("java");
 }
}

本节源码

源码: https://github.com/lltx/dgs-demo
DGS 官网: https://netflix.github.io/dgs

往期推荐


新年开箱 | Spring Authorization Server 全新的授权服务器上手

产品炸了 |  微信即将下线模板消息

RSocket | 替代 REST 的不二选择

后门 | Nacos 被爆严重安全漏洞

5分钟拥抱云原生 | SpringBoot 迁移至 Quarkus



浏览 19
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报