微服务API文档管理-Swagger

  - 今天学习的内容是配置swagger管理项目api文档接口,Swagger支持API自动生成同步在线文档,不需要手动编写接口文档。swagger生成的文档支持在线测试。

一、项目中集成swagger

1. 导入swagger依赖

  • 在cloud-common模块的pom文件中导入swagger依赖,因为各个微服务模块都需要使用swagger,所以统一在common模块配置。
<properties>
    <springfox-swagger.version>2.9.2</springfox-swagger.version>
</properties>
<!-- springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${springfox-swagger.version}</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${springfox-swagger.version}</version>
</dependency>
  • 其他服务的pom文件需要导入common模块的依赖
<dependency>
    <groupId>jin.li.yun.com</groupId>
    <artifactId>cloud-common</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

2. 配置swagger文档描述

  • 在cloud-common模块中的config中创建CommonBean类,配置swagger文档描述信息。
    在这里插入图片描述
  • 配置swagger文档描述信息代码清单
package jin.li.yun.com.common.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangjiao
 * @since 2020/12/24
 */
@Slf4j
@EnableSwagger2
@Configuration("ccb")
@SuppressWarnings("all")
public class CommonBean {
  @Value("${spring.swagger.enable:true}")
  private boolean enableSwagger;

  @Bean
  public Docket api() {

    ParameterBuilder tokenPar = new ParameterBuilder();
    List<Parameter> pars = new ArrayList<>();
    tokenPar
        .name("Authorization")
        .description("令牌")
        .modelRef(new ModelRef("string"))
        .parameterType("header")
        .required(false)
        .build();
    pars.add(tokenPar.build());
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .enable(enableSwagger)
        .select()
        .apis(RequestHandlerSelectors.basePackage("jin.li.yun.com"))
        .paths(PathSelectors.any())
        .build()
        .globalOperationParameters(pars);
  }

  private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
        .title("项目接口文档")
        .description("项目描述")
        .contact(new Contact("wangjiao", "", ""))
        .version("2.0")
        .build();
  }
}
  • 在controller类上加上swagger注解
/**
 * @author WangJiao
 * @since 2020/12/15
 */
@Slf4j
@RequestMapping(value = "/mini/user")
@RestController(value = "miniUserC")
@Api("MINI 用户API")
public class UserController {
  @Resource private UserService service;

  /**
   * 用户登录授权
   *
   * @param req req
   * @return res
   */
  @PostMapping("/auth-token")
  @ApiOperation("认证接口")
  public ApiResult authToken(@Valid @RequestBody UserLoginReq req) {}
}
  • 实体类上加swagger注解
/**
 * 用户登录信息请求
 *
 * @author WangJiao
 * @since 2019-12-19
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("用户登录信息请求")
public class UserLoginReq implements Serializable {
  private static final long serialVersionUID = 1L;

  @NotBlank(message = "电话不能为空")
  @ApiModelProperty(value = "电话", example = "15675458912")
  private String tel;

  @NotBlank(message = "密码不能为空")
  @ApiModelProperty(value = "密码", example = "yyy23")
  private String password;

  public static UserLoginReq of() {
    return new UserLoginReq();
  }
}
  • 启动项目
    在这里插入图片描述
  • 访问swagger地址:http://localhost:5050/user/swagger-ui.html
    在这里插入图片描述
  • 如果访问swagger地址出现如下页面:😱 Could not render e, see the console.
    在这里插入图片描述
  • 原因:@Value(" s p r i n g . s w a g g e r . e n a b l e : f a l s e " ) 修 改 成 @ V a l u e ( " {spring.swagger.enable:false}")修改成@Value(" spring.swagger.enable:false")@Value("{spring.swagger.enable:true}")

3. 在线测试接口

  • 点击【Try it out】按钮进行测试。填入参数,点击【Execute】进行提交测试
    在这里插入图片描述
  • 测试结果
    在这里插入图片描述

二、Zuul中聚合多个服务Swagger

1. 配置swagger依赖

  • 在Zuul中进行聚合操作的原因是不需要每次都去访问独立服务的文档,通过网关统一整合这些服务文档,方便使用。
  • 在cloud-gateway模块的pom文件中导入Common模块的依赖;
<dependency>
    <groupId>jin.li.yun.com</groupId>
    <artifactId>cloud-common</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
  • 如果cloud-gateway模块没有导入Common模块依赖,则需要重新导入swagger依赖,且需要重新配置swagger文档描述信息CommonBean类,由于Common模块放置的都是公共使用的,所以不需要再重新去创建一遍了。
<properties>
    <springfox-swagger.version>2.9.2</springfox-swagger.version>
</properties>
<!-- springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${springfox-swagger.version}</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${springfox-swagger.version}</version>
</dependency>
  • 不用手动去整合所有服务信息,而是直接去读取eureka中的服务信息,只要是注册到eureka中的服务就都能整合进来;
  • 在config中编写SwaggerConfig配置类,实现SwaggerResourcesProvider接口;

2. swagger聚合类代码清单

package jin.li.yun.com.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import jin.li.yun.com.common.constant.Constant;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 聚合文档配置 zuul routers 映射具体服务的/v2/api-docs swagger
 *
 * @author wangjiao
 * @since 2020/12/23
 */
@EnableSwagger2
@Component
@Primary
@Slf4j
public class SwaggerConfig implements SwaggerResourcesProvider {

  @Autowired private DiscoveryClient discoveryClient;

  @Value("${spring.application.name}")
  private String applicationName;

  @Override
  public List<SwaggerResource> get() {
    List<SwaggerResource> resources = new ArrayList<>();
    // 排除自身,将其他的服务添加进去
    discoveryClient.getServices().stream()
        .filter(s -> !s.equals(applicationName))
        .forEach(
            name -> {
              log.info("get:服务实例名称[names:{}]", name);
             // 服务实例名是cloud-user,配置的实例名:spring.application.name: cloud-user
             // 配置的服务uri: server.servlet.context-path: /user
             // 我们的服务uri是去掉‘cloud-’的,
             // 例如:http://localhost:5070/user/mini/user/auth-token,所以要去除前缀的‘cloud-’
             // 如果实例名配置的和服务名相同,则可直接使用不需要进行下面划分操作
               String[] names = name.split(Constant.DEFAULT_STRING_SHORT_LINE);

              if (names.length == 2) {
                name = names[1];
                log.info("get:服务实例名称取后缀[name:{}]", name);
              }
              Optional<ServiceInstance> instanceOptional =
                  discoveryClient.getInstances(name).stream().findFirst();
              if (instanceOptional.isPresent()
                  && instanceOptional.get().getMetadata().containsKey("context-path")) {
                String contextPath = instanceOptional.get().getMetadata().get("context-path");
                log.info("get:context-path[contextPath:{}]", contextPath);
                // yml配置文件中配置了 server.servlet.context-path: /user,走下面逻辑
                resources.add(
                    swaggerResource(name, "/" + name + contextPath + "/v2/api-docs", "2.0"));
              } else {
                resources.add(swaggerResource(name, "/" + name + "/v2/api-docs", "2.0"));
              }
            });

    return resources;
  }

  private SwaggerResource swaggerResource(String name, String location, String version) {
    SwaggerResource swaggerResource = new SwaggerResource();
    swaggerResource.setName(name);
    swaggerResource.setLocation(location);
    swaggerResource.setSwaggerVersion(version);
    log.info("swaggerResource:[swaggerResource:{}]", JSON.toJSONString(swaggerResource));
    return swaggerResource;
  }
}

3. 启动项目测试

在这里插入图片描述

  • 访问网关端口,5070是网关端口:http://localhost:5070/swagger-ui.html,可以在一个窗口切换不同服务,比较方便。
    在这里插入图片描述
  • 截取服务实例名称日志
    在这里插入图片描述
    在这里插入图片描述
    :- 到这里,相信你已经get到了,赶快动手试试吧!!!
    在这里插入图片描述
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值