亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot使用GraphQL開發(fā)Web API實現(xiàn)方案示例講解

 更新時間:2023年04月04日 11:51:55   作者:Alphathur  
這篇文章主要介紹了SpringBoot使用GraphQL開發(fā)Web API實現(xiàn)方案,GraphQL是一個從服務(wù)端檢數(shù)據(jù)的查詢語言。某種程度上,是REST、SOAP、或者gRPC的替代品

前言

傳統(tǒng)的Restful API 存在諸多的問題,首先它無法控制返回的字段,前端也無法預(yù)判后端的返回結(jié)果,另外不同的返回結(jié)果對應(yīng)不同的請求地址,這就導(dǎo)致了多次請求的問題。而GraphQL正是基于這樣的背景而構(gòu)建出來的API查詢語言,相對于傳統(tǒng)Restful API 它具有以下幾個優(yōu)點:

  • 靈活性:GraphQL 可以根據(jù)客戶端的需求靈活地查詢數(shù)據(jù),而不是像 RESTful API 那樣返回固定結(jié)構(gòu)的數(shù)據(jù)。
  • 減少網(wǎng)絡(luò)請求:GraphQL 允許客戶端在一次請求中獲取多個資源,這有助于減少網(wǎng)絡(luò)請求的數(shù)量和提高性能。
  • 強類型:GraphQL 有一種強類型系統(tǒng),客戶端可以在編譯時檢測到查詢中的錯誤,這有助于減少運行時錯誤。
  • 可緩存:GraphQL 具有可緩存性,這意味著服務(wù)器可以緩存查詢的結(jié)果,從而提高性能和可伸縮性。
  • 文檔化:GraphQL 具有自我文檔化的能力,使得開發(fā)者可以快速了解 API 的結(jié)構(gòu)和功能。

Spring Boot中GraphQL的實現(xiàn)方案

如果后端語言為Java,那么GraphQL Java則是實現(xiàn)GraphQL的基礎(chǔ)庫。另外Spring已經(jīng)整合了GraphQL,如果項目中使用了Spring,那么更加推薦Spring GraphQL。

Spring GraphQL的開發(fā)總體分為如下幾個步驟

添加 Spring GraphQL 依賴項

在您的項目中添加 Spring GraphQL 依賴項。您可以通過 Maven 或 Gradle 等構(gòu)建工具來添加依賴項。例如,如果您使用 Maven,則可以添加以下依賴項

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-graphql</artifactId>
        </dependency>

定義 GraphQL Schema

在您的應(yīng)用程序中定義 GraphQL Schema。Schema 定義了可查詢的類型和字段。您可以使用 SDL(Schema Definition Language)或編程方式定義 Schema。

對于Spring Boot 工程來說schema文件放到resources/graphql/目錄下,文件名后綴graphqls,下面是我定義一個的簡單的schema.graphqls。

它指定了兩個查詢實現(xiàn),author(id:Int)表示通過id查詢Author,allAuthors則表示查詢Author數(shù)組。

schema {
    query: Query
}

type Query {
    author(id:Int): Author
    allAuthors: [Author]
}

type Author {
    id:Int
    firstName:String
    lastName:String
    email:String
    birthdate:String
}

實現(xiàn)RuntimeWiringConfigurer

RuntimeWiringConfigurer是實現(xiàn)GraphQL獲取數(shù)據(jù)的核心,使用GraphQL并不能直接去掉Mybatis/Jpa這類持久層框架,從數(shù)據(jù)庫獲取數(shù)據(jù)仍然需要這類框架的支持。

而RuntimeWiringConfigurer則類似于Spring中的service層,它是實現(xiàn)基礎(chǔ)數(shù)據(jù)的核心。

以下是一個簡單示例:

@Component
public class AuthorWiring implements RuntimeWiringConfigurer {
    private final AuthorRepository authorRepository;
    public AuthorWiring(AuthorRepository authorRepository) {
        this.authorRepository = authorRepository;
    }
    @Override
    public void configure(RuntimeWiring.Builder builder) {
        builder.type("Query", typeWiring -> typeWiring
                        .dataFetcher("allAuthors", environment -> authorRepository.findAll())
                        .dataFetcher("author", environment -> authorRepository.getReferenceById(environment.getArgument("id")))
    }
}

這里configure方法內(nèi)部分別定義了兩個DataFetcher對象,用來指定author和allAuthors查詢數(shù)據(jù)的方式,可以看出依然是通過JPA去查詢數(shù)據(jù)。

定義GraphQL Controller

我么定義GraphQLController用來接收web請求的入?yún)?,示例如下?/p>

@RestController
@RequestMapping("graphql")
public class GraphQLController {
    private final GraphQL graphQL;
    @Autowired
    public GraphQLController(GraphQlSource graphQlSource) {
        graphQL = graphQlSource.graphQl();
    }
    @PostMapping("query")
    public ResponseEntity<Object> query(@RequestBody String query) {
        ExecutionResult result = graphQL.execute(query);
        return ResponseEntity.ok(result.getData());
    }
}

代碼中GraphQL對象是執(zhí)行查詢的入口,但GraphQL只有一個私有的構(gòu)造方法,所以不能直接注入,必須通過注入GraphQlSource的方式來獲取GraphQL對象。

注意在GraphQL中我們只能使用String來接收參數(shù),無法使用model對象,這是因為Graph請求參數(shù)并不是json結(jié)構(gòu)。

測試Graph請求

我們創(chuàng)建一個graphql.http的文件,用于在idea中執(zhí)行http請求

### Send POST request with json body
POST http://localhost:8080/graphql/query
Content-Type: application/json

{
  author(id: 1) {
    id
    firstName
    lastName
    birthdate
  }
}

### Send POST request with json body
POST http://localhost:8080/graphql/query
Content-Type: application/json

{
  allAuthors {
    id
    firstName
    lastName
    birthdate
  }
}

運行author(id: 1) 的查詢,可以看到正常返回結(jié)果了。如果我們只需要 firstName和lastName兩個字段,那么在請求入?yún)⒅兄苯尤サ鬷d和birthdate就好了,而不用改動任何后端代碼。

完整項目已上傳github ?? graphql-demo

到此這篇關(guān)于SpringBoot使用GraphQL開發(fā)Web API實現(xiàn)方案示例講解的文章就介紹到這了,更多相關(guān)SpringBoot GraphQL內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論