• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
思想人生从关注生活开始
博客园    首页    新随笔    联系   管理    订阅  订阅

集成SWAGGER2服务-spring cloud 入门教程

Swagger 是最流行的用于设计、构建和记录 RESTful API 的工具。它与 Spring Boot 有很好的集成。要将其与 Spring 结合使用,我们需要向 Maven管理文件中 添加以下两个依赖项pom.xml。

1
2
3
4
5
6
7
8
9
10
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>

单个 Spring Boot 服务的 Swagger 配置非常简单。如果您想为多个分离的微服务创建一个文档,则复杂程度更高。此类文档应在 API 网关上可用。在下图中,您可以看到我们示例解决方案的架构。

 

 

 

 

首先,我们应该在每个微服务上配置 Swagger。要启用它,我们必须@EnableSwagger2在主类上声明。在应用程序启动期间,Swagger 库将根据源代码自动生成 API 文档。进程由Docket @Bean控制,在主类中声明。我们还使用apiInfo方法设置了一些其他属性,如标题、作者和描述。默认情况下,Swagger 为所有 REST 服务生成文档,包括由 Spring Boot 创建的服务。我们希望将文档仅限于@RestController位于com.microservices.advanced.account.api包中的文档。

 

 

 

1
2
3
4
5
6
7
8
9
10
    @Bean
    public Docket api() throws IOException, XmlPullParserException {
        MavenXpp3Reader reader = new MavenXpp3Reader();
        Model model = reader.read(new FileReader("pom.xml"));
        return new Docket(DocumentationType.SWAGGER_2)
          .select()
          .apis(RequestHandlerSelectors.basePackage("com.microservices.advanced.account.api"))
          .paths(PathSelectors.any())
          .build().apiInfo(new ApiInfo("Account Service Api Documentation", "Documentation automatically generated", model.getParent().getVersion(), null, new Contact("Jack.Yang", "**@163.com", "**@163.com"), null, null));
}

 

 

 

这是我们的 API RESTful 控制器。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@RestController
public class AccountController {
 
    @Autowired
    AccountRepository repository;
 
    protected Logger logger = Logger.getLogger(AccountController.class.getName());
 
    @RequestMapping(value = "/accounts/{number}", method = RequestMethod.GET)
    public Account findByNumber(@PathVariable("number") String number) {
        logger.info(String.format("Account.findByNumber(%s)", number));
        return repository.findByNumber(number);
    }
 
    @RequestMapping(value = "/accounts/customer/{customer}", method = RequestMethod.GET)
    public List findByCustomer(@PathVariable("customer") String customerId) {
        logger.info(String.format("Account.findByCustomer(%s)", customerId));
        return repository.findByCustomerId(customerId);
    }
 
    @RequestMapping(value = "/accounts", method = RequestMethod.GET)
    public List findAll() {
        logger.info("Account.findAll()");
        return repository.findAll();
    }
 
    @RequestMapping(value = "/accounts", method = RequestMethod.POST)
    public Account add(@RequestBody Account account) {
        logger.info(String.format("Account.add(%s)", account));
        return repository.save(account);
    }
 
    @RequestMapping(value = "/accounts", method = RequestMethod.PUT)
    public Account update(@RequestBody Account account) {
        logger.info(String.format("Account.update(%s)", account));
        return repository.save(account);
    }
 
}

每个微服务上都存在类似的 Swagger 配置。API 文档位于http://localhost:/swagger-ui.html 下。现在,我们希望为所有微服务启用一个嵌入网关的文档。这是 Spring@Component实现SwaggerResourcesProvider接口,它覆盖 Spring 上下文中存在的默认提供程序配置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Component
@Primary
@EnableAutoConfiguration
public class DocumentationController implements SwaggerResourcesProvider {
 
    @Override
    public List get() {
        List resources = new ArrayList<>();
        resources.add(swaggerResource("account-service", "/api/account/v2/api-docs", "2.0"));
        resources.add(swaggerResource("customer-service", "/api/customer/v2/api-docs", "2.0"));
        resources.add(swaggerResource("product-service", "/api/product/v2/api-docs", "2.0"));
        resources.add(swaggerResource("transfer-service", "/api/transfer/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);
        return swaggerResource;
    }
 
}

所有微服务 api-docs 都作为 Swagger 资源添加。位置地址通过 Zuul 网关代理。这是网关路由配置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
zuul:
  prefix: /api
  routes:
    account:
      path: /account/**
      serviceId: account-service
    customer:
      path: /customer/**
      serviceId: customer-service
    product:
      path: /product/**
      serviceId: product-service
    transfer:
      path: /transfer/**
      serviceId: transfer-service

现在,API 文档在网关地址http://localhost:8765/swagger-ui.html下可用。您可以在下图中看到它如何查找帐户服务。我们可以在标题面板内的组合框中选择源服务。

 

 

通过提供UIConfiguration @Bean. 在下面的代码中,我通过将“list”设置为第二个构造函数参数 - docExpansion 来更改默认操作扩展级别。

1
2
3
4
5
@Bean
UiConfiguration uiConfig() {
    return new UiConfiguration("validatorUrl", "list", "alpha", "schema",
            UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false, true, 60000L);
}

您可以展开每个操作以查看详细信息。每个操作都可以通过提供所需参数并单击Try it out来测试!按钮。

 

 

 

使用 Zuul、Ribbon、Feign、Eureka 和 Sleuth、Zipkin 创建简单spring cloud微服务用例-spring cloud 入门教程
微服务集成SPRING CLOUD SLEUTH、ELK 和 ZIPKIN 进行监控-spring cloud 入门教程
使用Hystrix 、Feign 和 Ribbon构建微服务-spring cloud 入门教程

使用 Spring Boot Admin 监控微服务-spring cloud 入门教程

基于Redis做Spring Cloud Gateway 中的速率限制实践-spring cloud 入门教程
集成SWAGGER2服务-spring cloud 入门教程
Hystrix 简介-spring cloud 入门教程
Hystrix 原理深入分析-spring cloud 入门教程 
使用Apache Camel构建微服务-spring cloud 入门教程
集成 Kubernetes 来构建微服务-spring cloud 入门教程
集成SPRINGDOC OPENAPI 的微服务实践-spring cloud 入门教程
SPRING CLOUD 微服务快速指南-spring cloud 入门教程
基于GraphQL的微服务实践-spring cloud 入门教程
最火的Spring Cloud Gateway 为经过身份验证的用户启用速率限制实践-spring cloud 入门教程
posted @ 2021-08-16 15:25  JackYang  阅读(966)  评论(1)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3