前言
不管是做什么项目,都避免不了一个问题,怎样合理管理以及实时查询我的接口文档呢?后台人员写好接口必然要与前台人员对接,少不了的就是沟通,有时候一句两句确实说不清楚,但是有了Swagger之后呢?接口说明一目了然,-------废话不多说,直接开始
版本对应关系
- boot版本:2.0.8
- cloud版本:Edgware.SR6
- zuul版本:1.4.7.RELEASE
- mysql版本:5.1.47
- mybatis-plus:2.2.0
根pom(父工程)
父工程直接引用swagger相关依赖,只要是该工程下子module都会集成这个依赖
- 说明:
- com.spring4all 这个依赖就相当于封装了swagger的一些基础依赖
<dependencyManagement>
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.7.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.3</version>
</dependency>
</dependencyManagement>
网关服务(zuul-server)
微服务中通过网关转发请求到某个服务,它的原理就是实现了反向代理及负载均衡
- 核心就在zuul.routes这个配置,后续会读取相关服务
核心配置文件:
server:
port: 5555
spring:
application:
name: zuul-server
#mysql基础配置
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/myxue?characterEncoding=utf-8
eureka:
instance:
hostname: localhost
#指定访问本机IP
prefer-ip-address: true
client:
#被注册中心eureka发现并注册
fetch-registry: true
register-with-eureka: true
service-url:
defaultZone: http://localhost:8761/eureka
zuul:
prefix: /api
#转发服务
routes:
other:
path: /other-server/**
serviceId: other-server
show:
path: /show-server/**
serviceId: show-server
#配置mybatis-plus打印sql语句于控制台
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#开启驼峰命名转换
map-underscore-to-camel-case: true
#错误响应配置时间
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 6000 #熔断响应时间
#ribbon超时配置 读取和等待时间都设置6秒
ribbon:
#熔断读取时间
ReadTimeout: 60000
#连接等待时间
ConnectTimeout: 60000
- 配置类
package com.xwl.zuulserver.provider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
/**
* @Auther: 薛
* @Date: 2020/7/9 17:16
* @Description:
*/
@EnableSwagger2
@Configuration
@Primary //多个bean时 此类优先使用
public class SwaggerZuulConfig implements SwaggerResourcesProvider {
//是否开启swagger,默认true-正式环境可选false即可
Boolean swaggerEnabled=true;
//网关读取转发服务类
@Autowired
RouteLocator routeLocator;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
// 是否开启
.enable(swaggerEnabled).select()
// 扫描的路径包
.apis(RequestHandlerSelectors.basePackage("com.xwl.zuulserver"))
// 指定路径处理PathSelectors.any()代表所有的路径
.paths(PathSelectors.any()).build().pathMapping("/");
}
//设置api信息-可根据爱好随意填写
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//swagger 设置标题
.title("骠骑撸码大都督API接口文档")
//描述
.description("整合就完事了~")
//作者信息
.contact(new Contact("薛文良", "https://www.baidu.com", "未知~"))
//版本
.version("1.0.0")
//服务URL
.termsOfServiceUrl("https://www.baidu.com")
.build();
}
//扫描上诉配置文件application.yml中的其它服务
@Override
public List<SwaggerResource> get() {
//利用routeLocator动态引入微服务
List<SwaggerResource> resources = new ArrayList<>();
//网关服务默认添加
resources.add(swaggerResource("网关服务","/v2/api-docs","1.0"));
//循环 使用Lambda表达式简化代码
routeLocator.getRoutes().forEach(route ->{
//动态获取-过滤掉服务后缀/**
resources.add(swaggerResource(route.getId(),route.getFullPath().replace("**", "v2/api-docs"), "1.0"));
});
return resources;
}
private SwaggerResource swaggerResource(String name,String location, String version) {
SwaggerResource swaggerResource = new SwaggerResource();
//这里可以忽略,我为了演示方便加了个判断业务,实际开发中应该是有一个枚举或者在配置文件中声明出服务serviceId对应服务名称
String serverName="";
if (name.equals("网关服务")){
serverName="网关服务";
}else if (name.equals("other")){
serverName="系统服务";
}else {
serverName="业务服务";
}
swaggerResource.setName(serverName);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion(version);
return swaggerResource;
}
}
- 启动类
package com.xwl.zuulserver;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* 网关注入注册中心
*/
//Boot启动必须类
@SpringBootApplication
//开启网关转发服务
@EnableZuulProxy
//被注册中心发现
@EnableEurekaClient
//扫描Mapper
@MapperScan("com.xwl.zuulserver.mapper")
public class ZuulServerApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulServerApplication.class, args);
}
/**
* 跨域解决
* @return
*/
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.setMaxAge(18000L);
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
-
添加swagger支持API
-
这里可以参考Swagger使用说明
给若干Class添加Swagger支持之后启动网关zuul-server -
访问地址http://localhost:5555/doc.html
-
如图所示
show-server(业务服务)
核心配置
server:
port: 8222
spring:
application:
name: show-server
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/myxue?characterEncoding=utf-8
eureka:
instance:
hostname: localhost
prefer-ip-address: true
client:
fetch-registry: true
register-with-eureka: true
service-url:
default-Zone: http://localhost:8761/eureka
#配置mybatis-plus打印sql语句于控制台
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#开启驼峰命名转换
map-underscore-to-camel-case: true
- 核心配置类
package com.xwl.showserver.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @Auther: 薛
* @Date: 2020/7/9 17:07
* @Description:
*/
@EnableSwagger2
@Configuration
public class SwaggerConfig {
//是否开启swagger,,
Boolean swaggerEnabled=true;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
// 是否开启
.enable(swaggerEnabled).select()
// 扫描的路径包
.apis(RequestHandlerSelectors.basePackage("com.xwl.showserver"))
// 指定路径处理PathSelectors.any()代表所有的路径
.paths(PathSelectors.any()).build().pathMapping("/");
}
//设置api信息
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("骠骑撸码大都督API接口文档")
.description("整合就完事了~")
.contact(new Contact("薛文良", "https://www.baidu.com", "未知~"))
.version("1.0.0")
.termsOfServiceUrl("https://www.baidu.com")
.build();
}
}
- 启动类
package com.xwl.showserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @Auther: 薛
* @Date: 2020/7/7 10:15
* @Description:
*/
@SpringBootApplication
@EnableDiscoveryClient
public class ShowApplication {
public static void main(String[] args) {
SpringApplication.run(ShowApplication.class,args);
}
}
启动show-server
然后再次启动zuul-server
再次访问swagger接口文档 http://localhost:5555/doc.html
如图所示可以切换访问show-server服务的接口咯
other-server我就不举例了和show-server基本相同
联系博主
有任何不懂的都可以找我,助人为乐,共同进步
QQ:2509647976
wx:x331191249