首页  

Java实现GraphQL服务     所属分类 graphQL 浏览量 279
GraphQL是一种从服务器检索数据的查询语言 ,可替代 REST SOAP gRPC 等 

GraphQL is a query language 
API defines how a client can load data from a server.


获取id为 book-1 的书籍的详细信息
{
  bookById(id: "book-1"){
    id
    name
    pageCount
    author {
      firstName
      lastName
    }
  }
}

查询指定ID的书籍
返回书的id,名字,页数和作者
对于作者,返回名字和姓氏


响应为JSON

{
  "bookById":
  {
    "id":"book-1",
    "name":"Java is good",
    "pageCount":221,
    "author": {
      "firstName":"hello",
      "lastName":"java"
    }
  }
}


GraphQL 特性  静态类型
GraphQL模式

type Query {
  bookById(id: ID): Book
}

type Book {
  id: ID
  name: String
  pageCount: Int
  author: Author
}

type Author {
  id: ID
  firstName: String
  lastName: String
}




Java 实现 GraphQL服务器的主要步骤
1. 定义GraphQL模式
2. 决定如何获取查询的实际数据


GraphQL  GraphQLSchema  DataFetcher



springboot 2.7.10 org.springframework.boot:spring-boot-starter-web org.springframework.boot:spring-boot-starter-graphql com/graphql-java/graphql-java/18.4/graphql-java-18.4.jar com/graphql-java/java-dataloader/3.1.2/java-dataloader-3.1.2.jar s.b.a.g.s.GraphQlWebMvcAutoConfiguration : GraphQL endpoint HTTP POST /graphql o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8060 (http) with context path '' postman post http://127.0.0.1:8060/graphql { bookById(id: "book-1"){ id name pageCount author { firstName lastName } } } 返回值 { "data": { "bookById": { "id": "book-1", "name": "Harry Potter and the Philosopher's Stone", "pageCount": 223, "author": { "firstName": "Joanne", "lastName": "Rowling" } } } } { bookById(id: "book-21"){ id name pageCount author { firstName lastName } } } { "data": { "bookById": null } }
使用参数 query($id:ID){ bookById(id: $id){ id name pageCount author { firstName lastName } } } GRAPHQL VARIABLES {"id":"book-2"}
post { "query":"{查询语句}" "variables":"{参数和参数值}" }
例子代码 https://gitee.com/dyyx/work2024/tree/master/demo/graphql-java-demo https://www.graphql-java.com/tutorials/getting-started-with-spring-boot graphql入门 https://graphql.github.io/learn/

上一篇     下一篇
SkyWalking 慢sql 数据获取 ,graphQL 接口 例子

西湖古诗词

SkyWalking GraphQL API 查询实例

杭州西湖三十景

GraphQL 基础

skywalking PromQL 服务 grafana 整合 图表配置