微服务技术系列教程(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.展开其中的一个接口

可以看到描述:

目录
相关文章
|
5月前
|
算法 Java 微服务
【SpringCloud(1)】初识微服务架构:创建一个简单的微服务;java与Spring与微服务;初入RestTemplate
微服务架构是What?? 微服务架构是一种架构模式,它提出将单一应用程序划分为一组小的服务,服务之间互相协调、互相配合,为用户提供最终价值。 每个服务允许在其独立的进程中,服务于服务间采用轻量级的通信机制互相协作(通常是Http协议的RESTful API或RPC协议)。 每个服务都围绕着具体业务进行构建,并且能够被独立的部署到生产环境、类生产环境等。另外应当尽量避免统一的、集中式的服务管理机制,对具体的一个服务而言,应根据上下文,选择合适的语言、工具对其进行构建
580 126
|
5月前
|
负载均衡 算法 Java
【SpringCloud(2)】微服务注册中心:Eureka、Zookeeper;CAP分析;服务注册与服务发现;单机/集群部署Eureka;连接注册中心
1. 什么是服务治理? SpringCloud封装了Netfix开发的Eureka模块来实现服务治理 在传统pc的远程调用框架中,管理每个服务与服务之间依赖关系比较复杂,管理比较复杂,所以需要使用服务治理,管理服务于服务之间依赖关系,可以实现服务调用、负载均衡、容错等,实现服务发现与注册
370 1
|
5月前
|
负载均衡 Java API
《深入理解Spring》Spring Cloud 构建分布式系统的微服务全家桶
Spring Cloud为微服务架构提供一站式解决方案,涵盖服务注册、配置管理、负载均衡、熔断限流等核心功能,助力开发者构建高可用、易扩展的分布式系统,并持续向云原生演进。
|
6月前
|
监控 安全 Java
Spring Cloud 微服务治理技术详解与实践指南
本文档全面介绍 Spring Cloud 微服务治理框架的核心组件、架构设计和实践应用。作为 Spring 生态系统中构建分布式系统的标准工具箱,Spring Cloud 提供了一套完整的微服务解决方案,涵盖服务发现、配置管理、负载均衡、熔断器等关键功能。本文将深入探讨其核心组件的工作原理、集成方式以及在实际项目中的最佳实践,帮助开发者构建高可用、可扩展的分布式系统。
380 1
|
6月前
|
jenkins Java 持续交付
使用 Jenkins 和 Spring Cloud 自动化微服务部署
随着单体应用逐渐被微服务架构取代,企业对快速发布、可扩展性和高可用性的需求日益增长。Jenkins 作为领先的持续集成与部署工具,结合 Spring Cloud 提供的云原生解决方案,能够有效简化微服务的开发、测试与部署流程。本文介绍了如何通过 Jenkins 实现微服务的自动化构建与部署,并结合 Spring Cloud 的配置管理、服务发现等功能,打造高效、稳定的微服务交付流程。
741 0
使用 Jenkins 和 Spring Cloud 自动化微服务部署
|
6月前
|
Kubernetes Java 微服务
Spring Cloud 微服务架构技术解析与实践指南
本文档全面介绍 Spring Cloud 微服务架构的核心组件、设计理念和实现方案。作为构建分布式系统的综合工具箱,Spring Cloud 为微服务架构提供了服务发现、配置管理、负载均衡、熔断器等关键功能的标准化实现。本文将深入探讨其核心组件的工作原理、集成方式以及在实际项目中的最佳实践,帮助开发者构建高可用、可扩展的分布式系统。
584 0
|
SpringCloudAlibaba API 开发者
新版-SpringCloud+SpringCloud Alibaba
新版-SpringCloud+SpringCloud Alibaba
|
12月前
|
负载均衡 Dubbo Java
Spring Cloud Alibaba与Spring Cloud区别和联系?
Spring Cloud Alibaba与Spring Cloud区别和联系?
|
人工智能 SpringCloudAlibaba 自然语言处理
SpringCloud Alibaba AI整合DeepSeek落地AI项目实战
在现代软件开发领域,微服务架构因其灵活性、可扩展性和模块化特性而受到广泛欢迎。微服务架构通过将大型应用程序拆分为多个小型、独立的服务,每个服务运行在其独立的进程中,服务与服务间通过轻量级通信机制(通常是HTTP API)进行通信。这种架构模式有助于提升系统的可维护性、可扩展性和开发效率。
4580 2

热门文章

最新文章