微服务技术系列教程(26) - SpringCloud- 接口管理Swagger

简介: 微服务技术系列教程(26) - SpringCloud- 接口管理Swagger

引言

代码已提交到Github,有兴趣的同学可以看看:https://github.com/ylw-github/SpringCloud-Zuul-Demo/tree/master/repository/Swagger-Demo

随着微服务架构体系的发展和应用, 为了前后端能够更好的集成与对接,同时为了项目的方便交付,每个项目都需要提供相应的API文档。

提供的对象有: PC端、微信端、H5端、移动端(安卓和IOS端)

传统的API文档编写存在以下几个问题:

  • 对API文档进行更新的时候,需要通知前端开发人员,导致文档更新交流不及时;
  • API接口返回信息不明确。
  • 大公司中肯定会有专门文档服务器对接口文档进行更新。
  • 缺乏在线接口测试,通常需要使用相应的API测试工具,比如postman、SoapUI等
  • 接口文档太多,不便于管理。

为了解决传统API接口文档维护的问题,为了方便进行测试后台Restful接口并实现动态的更新,因而引入Swagger接口工具。

1. Swagger

Swagger Demo的代码已提交到Github,有兴趣的同学可以看看:https://github.com/ylw-github/SpringCloud-Zuul-Demo/tree/master/repository/Swagger-Demo

Swagger具有以下优点:

  • 功能丰富:支持多种注解,自动生成接口文档界面,支持在界面测试API接口功能;
  • 及时更新:开发过程中花一点写注释的时间,就可以及时的更新API文档,省心省力;
  • 整合简单:通过添加pom依赖和简单配置,内嵌于应用中就可同时发布API接口文档界面,不需要部署独立服务。

1.1 Swagger集成步骤

1.新建Maven项目Swagger-Demo

2.添加Maven依赖

<parent>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>2.0.1.RELEASE</version>
 </parent>
 <dependencies>
     <!-- SpringBoot整合Web组件 -->
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
     </dependency>
     <!--SpringBoot swagger2 -->
     <dependency>
         <groupId>io.springfox</groupId>
         <artifactId>springfox-swagger2</artifactId>
         <version>2.8.0</version>
     </dependency>
     <!--SpringBoot swagger2 -UI -->
     <dependency>
         <groupId>io.springfox</groupId>
         <artifactId>springfox-swagger-ui</artifactId>
         <version>2.8.0</version>
     </dependency>
 </dependencies>

3.添加SwaggerConfig

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
                // api扫包
                .apis(RequestHandlerSelectors.basePackage("com.ylw.swagger.api")).paths(PathSelectors.any()).build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("学生信息管理系统").description("对学生信息进行管理")
                .termsOfServiceUrl("http://www.xxx.com")
                // .contact(contact)
                .version("1.0").build();
    }
}

4.API注释

@RestController
@RequestMapping("api")
@Api("学生信息管理系统相关的api")
public class StudentController {
    private static final Logger logger = LoggerFactory.getLogger(StudentController.class);
    @ApiOperation(value = "新增学生信息", notes = "新增学生信息:用户名、性别、年龄")
    @ApiResponses({
            @ApiResponse(code = 200, message = "校验成功"),
            @ApiResponse(code = 400, message = "校验失败"),
            @ApiResponse(code = 401, message = "参数不合法"),
            @ApiResponse(code = 500, message = "系统异常"),
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "学生名字", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sex", value = "性别", required = false, dataType = "String"),
            @ApiImplicitParam(name = "age", value = "年龄", required = false, dataType = "Integer"),
    })
    @RequestMapping(value = "/addStudent/{userName}/{sex}/{age}", method = RequestMethod.POST)
    public Response addStudent(@PathVariable String userName, @PathVariable String sex, @PathVariable Integer age) {
        logger.info("新增学生信息操作");
        return new Response(200, "新增学生信息成功!");
    }
    @ApiOperation(value = "删除学生信息", notes = "删除学生信息:用户名、性别、年龄")
    @ApiResponses({
            @ApiResponse(code = 200, message = "校验成功"),
            @ApiResponse(code = 400, message = "校验失败"),
            @ApiResponse(code = 401, message = "参数不合法"),
            @ApiResponse(code = 500, message = "系统异常"),
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "学生id", required = true, dataType = "String"),
    })
    @RequestMapping(value = "/delStudent/{uuid}", method = RequestMethod.DELETE)
    public Response delStudent(@PathVariable String uuid) {
        logger.info("删除学生信息操作");
        return new Response(200, "删除学生信息成功!");
    }
    @ApiOperation(value = "修改学生信息", notes = "修改学生信息:用户名、性别、年龄")
    @ApiResponses({
            @ApiResponse(code = 200, message = "校验成功"),
            @ApiResponse(code = 400, message = "校验失败"),
            @ApiResponse(code = 401, message = "参数不合法"),
            @ApiResponse(code = 500, message = "系统异常"),
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "学生id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "userName", value = "学生名字", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sex", value = "性别", required = false, dataType = "String"),
            @ApiImplicitParam(name = "age", value = "年龄", required = false, dataType = "Integer"),
    })
    @RequestMapping(value = "/updateStudent/{id}/{userName}/{sex}/{age}", method = RequestMethod.POST)
    public Response updateStudent(@PathVariable String id, @PathVariable String userName, @PathVariable String sex, @PathVariable Integer age) {
        logger.info("修改学生信息操作");
        return new Response(200, "修改学生信息成功!");
    }
    @ApiOperation(value = "查询学生信息", notes = "查询学生信息:用户名、性别、年龄")
    @ApiResponses({
            @ApiResponse(code = 200, message = "校验成功"),
            @ApiResponse(code = 400, message = "校验失败"),
            @ApiResponse(code = 401, message = "参数不合法"),
            @ApiResponse(code = 500, message = "系统异常"),
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "学生id", required = true, dataType = "String"),
    })
    @RequestMapping(value = "/getStudent/{id}", method = RequestMethod.GET)
    public Response getStudent(@PathVariable String id) {
        logger.info("修改学生信息操作");
        return new Response(200, "修改学生信息成功!");
    }
}

5.浏览器访问

访问网址:http://localhost:8099/swagger-ui.html#/,可以看到接口文档自动生成了。

6.展开其中的一个接口

可以看到描述:

目录
相关文章
|
缓存 Java API
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
本文介绍了在Spring Boot中配置Swagger2的方法。通过创建一个配置类,添加`@Configuration`和`@EnableSwagger2`注解,使用Docket对象定义API文档的详细信息,包括标题、描述、版本和包路径等。配置完成后,访问`localhost:8080/swagger-ui.html`即可查看接口文档。文中还提示了可能因浏览器缓存导致的问题及解决方法。
1614 0
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
|
JSON Java API
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的使用
本文详细介绍了Swagger2的使用方法,包括在Spring Boot项目中的配置与应用。重点讲解了Swagger2中常用的注解,如实体类上的`@ApiModel`和`@ApiModelProperty`,Controller类上的`@Api`、`@ApiOperation`以及参数上的`@ApiParam`等。通过示例代码展示了如何为实体类和接口添加注解,并在页面上生成在线接口文档,实现接口测试。最后总结了Swagger的优势及其在项目开发中的重要性,提供了课程源代码下载链接供学习参考。
1234 0
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的使用
|
Java Maven 微服务
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的 maven 依赖
在项目中使用Swagger2工具时,需导入Maven依赖。尽管官方最高版本为2.8.0,但其展示效果不够理想且稳定性欠佳。实际开发中常用2.2.2版本,因其稳定且界面友好。以下是围绕2.2.2版本的Maven依赖配置,包括`springfox-swagger2`和`springfox-swagger-ui`两个模块。
777 0
|
前端开发 Java API
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档—— Swagger 简介
第6课介绍了在Spring Boot中集成Swagger2以展示在线接口文档的方法。随着前后端分离架构的发展,API文档成为连接前端与后端开发的重要纽带。然而,代码更新频繁导致文档难以同步维护,Swagger2解决了这一问题。通过Swagger,在线API文档不仅方便了接口调用方查看和测试,还支持开发者实时测试接口数据。本文使用Swagger 2.2.2版本,讲解如何在Spring Boot项目中导入并配置Swagger2工具,从而高效管理接口文档。
597 0
|
监控 安全 Java
Spring Cloud 微服务治理技术详解与实践指南
本文档全面介绍 Spring Cloud 微服务治理框架的核心组件、架构设计和实践应用。作为 Spring 生态系统中构建分布式系统的标准工具箱,Spring Cloud 提供了一套完整的微服务解决方案,涵盖服务发现、配置管理、负载均衡、熔断器等关键功能。本文将深入探讨其核心组件的工作原理、集成方式以及在实际项目中的最佳实践,帮助开发者构建高可用、可扩展的分布式系统。
791 1
|
SpringCloudAlibaba Java Nacos
尚硅谷SpringCloud教程 笔记
本文介绍了基于Spring Cloud Alibaba构建的cloud-demo工程创建步骤,包括父模块及子模块的配置。父模块采用pom打包方式,定义了Java 8、Spring Boot 2.4.2、Spring Cloud 2020.0.1及Spring Cloud Alibaba 2021.1版本。包含三个主要模块:services(依赖Nacos)、service-order和service-product(均依赖spring-boot-starter-web)。同时提供了discoveryClient的测试代码,展示服务发现功能的实现与验证过程。
903 12
尚硅谷SpringCloud教程 笔记
|
Kubernetes Java 微服务
Spring Cloud 微服务架构技术解析与实践指南
本文档全面介绍 Spring Cloud 微服务架构的核心组件、设计理念和实现方案。作为构建分布式系统的综合工具箱,Spring Cloud 为微服务架构提供了服务发现、配置管理、负载均衡、熔断器等关键功能的标准化实现。本文将深入探讨其核心组件的工作原理、集成方式以及在实际项目中的最佳实践,帮助开发者构建高可用、可扩展的分布式系统。
1088 0
|
SpringCloudAlibaba JavaScript Dubbo
【SpringCloud Alibaba系列】Dubbo dubbo-admin安装教程篇
本文介绍了 Dubbo-Admin 的安装和使用步骤。Dubbo-Admin 是一个前后端分离的项目,前端基于 Vue,后端基于 Spring Boot。安装前需确保开发环境(Windows 10)已安装 JDK、Maven 和 Node.js,并在 Linux CentOS 7 上部署 Zookeeper 作为注册中心。
4526 1
【SpringCloud Alibaba系列】Dubbo dubbo-admin安装教程篇
|
监控 JavaScript 数据可视化
建筑施工一体化信息管理平台源码,支持微服务架构,采用Java、Spring Cloud、Vue等技术开发。
智慧工地云平台是专为建筑施工领域打造的一体化信息管理平台,利用大数据、云计算、物联网等技术,实现施工区域各系统数据汇总与可视化管理。平台涵盖人员、设备、物料、环境等关键因素的实时监控与数据分析,提供远程指挥、决策支持等功能,提升工作效率,促进产业信息化发展。系统由PC端、APP移动端及项目、监管、数据屏三大平台组成,支持微服务架构,采用Java、Spring Cloud、Vue等技术开发。
851 7

热门文章

最新文章