自动生成spring RESTful web服务端和客户端代码

在使用springboot开发 RESTFul 接口的时候,我们往往需要定义 model 实体-> request mapping定义路由 -> 业务逻辑处理.等步骤. 对于不同的业务前两部代码的相似度非常高,今天我们将介绍一种工具自动为我们生成这部分代码,让开发专注于业务逻辑的编写,且生成的代码都是异步接口(reactive响应式编程).
在使用之前首先需要下载 openapi-generator-cli-4.0.3.jar .

下面以获取和增加用户信息为例子

编写yaml文件

userapi.yaml

openapi: 3.0.0
servers:
  - url: '{apiRoot}/'
    variables:
      apiRoot:
        default: http://localhost
info:
  description: User info Service
  version: "1.0.0"
  title: User info Service
paths:
  /user/query:
    get:
      summary: Get user info by ID
      parameters:
        - name: id
          in: query
          description: user id
          required: true
          schema:
            type: string
          example: 12345
      responses:
        '200':
          description: "successful operation"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/UserInfo"
        '404':
          $ref: '#/components/responses/404'
  /user/add:
    post:
      summary: Add user info
      tags:
        - Add user info
      requestBody:
        description: Inforation to add
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/UserInfo"
      responses:
        '200':
          description: "No Content(successful operation)"
        '500':
          $ref: '#/components/responses/500'
components:
  schemas:
    UserInfo:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
        age:
          type: integer
        address:
          type: string
    ProblemDetails:
      type: object
      properties:
        success:
          type: boolean
        code:
          type: integer
        message:
          type: string
  responses:
    '404':
      description: Not Found
      content:
        application/problem+json:
          schema:
            $ref: '#/components/schemas/ProblemDetails'
    '500':
      description: Internal Server Error
      content:
        application/problem+json:
          schema:
            $ref: '#/components/schemas/ProblemDetails'

生成服务端代码

定义json文件描述包的信息
cat server.json
{
“basePackage”:“com.hjl.server”,
“configPackage”:“com.hjl.server.config”,
“apiPackage”:“com.hjl.server.api”,
“modelPackage”:“com.hjl.server.model”,
“groupId”:“com.hjl.server”,
“artifactId”:“user-server”,
“dateLibrary”:“java8”,
“async”:“true”,
“reactive”:“true”,
“hideGenerationTimestamp”:“true”
}

生成server端代码
java -jar openapi-generator-cli-4.0.3.jar generate -i userapi.yaml -g spring -o server -c server.json

我们把生成的服务端代码拷贝到我们的工程,在gradle文件里添加下面依赖:
‘org.springframework.boot:spring-boot-starter-webflux’

编写服务端代码,代码生成之后我们只需专注业务逻辑部分的代码.
例如在生成的代码文件UserApiController.java中增加返回用户信息的代码如下:

@Controller
@RequestMapping("${openapi.userInfoService.base-path:}")
public class UserApiController implements UserApi {
	@Override
	public Mono<ResponseEntity<UserInfo>> userQueryGet(@NotNull @Valid String id, ServerWebExchange exchange) {
		UserInfo userInfo = new UserInfo();
		userInfo.setId("1000");
		userInfo.setName("lisi");
		userInfo.setAge(30);
		userInfo.setAddress("ChengDu SiChuang");
		return Mono.just(ResponseEntity.ok(userInfo));
	}
}

生成客户端代码

定义一个json文件描述包的信息
cat client.json
{
“basePackage”:“com.hjl.client”,
“configPackage”:“com.hjl.client.config”,
“apiPackage”:“com.hjl.client.api”,
“modelPackage”:“com.hjl.client.model”,
“groupId”:“com.hjl”,
“artifactId”:“user-client”,
“dateLibrary”:“java8”,
“library”:“webclient”,
“hideGenerationTimestamp”:“true”
}

生成client代码
java -jar openapi-generator-cli-4.0.3.jar generate -i userapi.yaml -g java -o client -c client.json

我们把生成的客户端代码拷贝到我们的工程,在gradle文件里添加下面依赖:
compile ‘io.projectreactor:reactor-core:3.3.4.RELEASE’
compile ‘io.projectreactor.netty:reactor-netty:0.9.6.RELEASE’
compile ‘org.springframework:spring-web’

调用生成的代码来查询用户信息

		ApiClient client = new ApiClient();
		client.setBasePath("http://127.0.0.1:8080");
		**//client可以作为全局定义,其是线程安全.**
		new GetUserInfoApi(client).userQueryGet("1").subscribe(userInfo -> System.out.println(userInfo));

调用成功会返回
UserInfo {
id: 1000
name: lisi
age: 30
address: ChengDu SiChuang
}]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值