当前位置: 首页 > 后端技术 > Java

SpringBoot+GraphQL是API的未来!

时间:2023-04-01 20:31:30 Java

来源:www.toutiao.com/i6929867921162273292前言在浅尝GraphQL一文中介绍了GraphQL及其基本使用。本文提供了一个基础的例子来描述如何快速应用一个基于springboot的web项目。graphql-java的官方文档:GraphQLJava和SpringBoot入门,提供了相关的依赖,可以快速配置,但是我真的不推荐使用这个库和相关的配置方式搭建脚手架。在实际开发中,业务比较复杂,有时候,会导致需要配置的业务代码越来越复杂。与下面的方法相比,代码复杂度比较高。本文提供了一种更加灵活快捷的方法,可以在springboot项目中快速应用开发。使用的依赖也和上面官方提供的不同,请注意区分。快速开始创建一个springboot项目,通过SpringInitializr快速构建。我选择的jdk版本和springboot版本如下,其他版本没有做过兼容性测试。点击下面的Generate按钮:打开项目结构如下,我删除了application.properties,换成了applicaiton.yml,因为我个人比较喜欢yaml的配置方式:导入相关依赖pom.xml配置如下:4.0.0org.springframework.bootspring-boot-starter-parent2.4.6com.xuxdgraphql.demo0.0.1-SNAPSHOTgraphql.demoSpringBoot的GraphQL演示项目1.81.81.8UTF-8UTF-81.18.2011.0.12.8.7org.springframework.bootspring-boot-starterorg.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-testtestorg.projectlomboklombok<版本>${lombok.version}providedcom.graphql-java-kickstartgraphql-java-tools${graphql-java-tools.version}com.google.code.gsongson<版本>${gson.version}org.springframework.bootspring-boot-maven-plugin初始化GraphQL实例我们将创建一个GraphQL实例并将其注册到spring容器中,代码如下:创建一个GraphQLProvider类:@ComponentpublicclassGraphQLProvider{privateGraphQLgraphQL;@AutowiredprivateIItemServiceitemService;@BeanpublicGraphQLgraphQL(){返回graphQL;}@PostConstructpublicvoidinit()throwsIOException{GraphQLSchemagraphQLSchema=SchemaParser.newParser().file("graphql/base.graphqls").resolvers(newQuery(),newMutation()).file("graphql/item.graphqls").resolvers(newItemResolver(itemService))//.file("book.graphqls")//.resolvers(newBookResolver())//其他定义在上面的例子中,继续添加.build().makeExecutableSchema();this.graphQL=graphQL.newGraphQL(graphQLSchema).build();}}关于*.graphqls或者相应的Resolver如ItemResolver,可以参考GraphQL的相关说明,这里只做了小的调整,相关代码如下:base.grqphqlsschema{#queryquery:Query#更新突变:Mutation}typeQuery{version:String}typeMutation{version:String}item.graphqls#定义一个查询类型extendtypeQuery{queryItemList:ItemList#定义一个查询项列表queryById(id:ID):Item}extendtypeMutation{updateName(param:Param):Item}#定义item字段类型Item{id:ID!代码:字符串!名称:字符串!}类型ItemList{itemList:[Item!]!#获取物品列表总计:Int!#获取物品总数}inputParam{id:ID!名称:字符串!}ItemResolver公共类ItemResolver实现GraphQLQueryResolver,GraphQLMutationResolver{privateIItemServiceitemService;publicItemResolver(IItemServiceitemService){this.itemService=itemService;}//对应ItemList.graphqls中的pqueryqueryItemList(){returnitemService.queryItemList();}publicItemqueryById(Longid){returnitemService.queryById(id);}publicItemupdateName(Paramparam){returnitemService.updateName(param);}}相关业务代码较多,不一一列举发布提供一个API,我们需要暴露一个接口来接收请求,做相关的处理,我们只需要提供一个接口即可。所以我们创建一个控制器:GraphqlController.@RestController@RequestMapping("/graphql")@LogpublicclassGraphqlController{@AutowiredprivateGraphQLgraphQL;@PostMappingpublicObjectexecute(@RequestBodyGraphqlRequestrequest){ExecutionInputexecutionInput=ExecutionInput.newquery(request.getQuery()).variables(request.getVariables()).build();Mapresult=newHashMap<>();ExecutionResultexecutionResult=graphQL.execute(executionInput);Listerrors=executionResult.getErrors();if(errors!=null&&!errors.isEmpty()){result.put("errors",错误);返回结果;}返回executionResult.getData();}}到这里一步,其实基本的功能都配置好了,可以启动项目进行相关测试了。整个项目的代码结构如下。我尝试使用比较常规的web项目结构(controller、service、dao等):测试示例中一共提供了3个接口,两个query和一个update,分别测试:ItemListqueryItemList();ItemqueryById(Longid);项目更新名称(Paramparam);查询所有项目的列表(只获取每个项目的代码和名称,以及列表的总数):根据ID查询,获取项目的id和名称并更新指定的ID项目名称更改项目ID为1编码为test到“javaproject”再次查看,可以看到结果更新了:结论这样整个项目GraphQL相关的基础配置就完成了,业务开发可以进行。近期热点文章推荐:1.1,000+Java面试题及答案(2021最新版)2.别在满屏的if/else中,试试策略模式,真的很好吃!!3.操!Java中xx≠null的新语法是什么?4、SpringBoot2.5发布,深色模式太炸了!5.《Java开发手册(嵩山版)》最新发布,赶快下载吧!感觉不错,别忘了点赞+转发!