引言
代码已上传至Github,有兴趣的同学可以下载来看看:https://github.com/ylw-github/SpringCloud-Zuul-Demo
上两篇文章讲了Zuul以及Swagger相关的概念:
本文将基于《微服务技术系列教程(25) - SpringCloud- 接口网关服务Zuul》项目的基础上整合Swagger,来管理所有的API。
1. Zuul整合Swagger
有以下几个项目:
- Eureka 注册中心
- Config Server 配置中心
- Service-ZUUL 网关服务
- APP-SERVICE-A 服务A
- APP-SERVICE-B 服务B
启动所有服务后如下:
1.1 服务A和服务B
1. 服务A和服务B添加Maven依赖
<!-- swagger-spring-boot --> <dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>1.7.0.RELEASE</version> </dependency>
2. 服务A和服务B配置application.yml
swagger: base-package: com.ylw.springcloud.eureka.a
3. 项目启动引入开启生成文档
添加:@EnableSwagger2Doc
@SpringBootApplication @EnableEurekaClient @EnableSwagger2Doc public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
1.2 网关服务
1. 添加Maven依赖
<!-- swagger-spring-boot --> <dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>1.7.0.RELEASE</version> </dependency>
2.新增DocumentationConfig类
@Component @Primary public class DocumentationConfig implements SwaggerResourcesProvider { @Override public List<SwaggerResource> get() { List resources = new ArrayList<>(); // app-itmayiedu-order resources.add(swaggerResource("app-service-a", "/api-a/v2/api-docs?userToken=123", "2.0")); resources.add(swaggerResource("app-service-b", "/api-b/v2/api-docs?userToken=123", "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; } }
3.启动类开启Swagger@EnableSwagger2Doc
@SpringBootApplication @EnableEurekaClient @EnableZuulProxy @EnableSwagger2Doc public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } // 注册到SpringBoot 容器 @Bean public TokenFilter accessFilter() { return new TokenFilter(); } // zuul配置能够使用config实现实时更新 @RefreshScope @ConfigurationProperties("zuul") public ZuulProperties zuulProperties() { return new ZuulProperties(); } }
1.3 测试
访问网址:http://localhost/swagger-ui.html#/
切换app-service-b:
使用Zuul集成Swagger成功!