1.在gateway网关层加入以下依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.4</version>
</dependency>
2.gateway网关层yml文件的路由配置:
gateway:
routes:
- id: cloud-provider-1
uri: lb://cloud-provider-1
predicates:
- Path=/test1/**
filters:
- StripPrefix=1
- id: cloud-provider-2
uri: lb://cloud-provider-2
predicates:
- Path=/test2/**
filters:
- StripPrefix=1
3.在gateway层增加2个配置文件:
第一个文件:
package com.oracle.cloud.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import springfox.documentation.swagger.web.*;
import java.util.Optional;
/**
* 获取api接口信息
*/
@RestController
public class SwaggerHandler {
@Autowired(required = false)
private SecurityConfiguration securityConfiguration;
@Autowired(required = false)
private UiConfiguration uiConfiguration;
private final SwaggerResourcesProvider swaggerResources;
@Autowired
public SwaggerHandler(SwaggerResourcesProvider swaggerResources) {
this.swaggerResources = swaggerResources;
}
@GetMapping("/swagger-resources/configuration/security")
public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));
}
@GetMapping("/swagger-resources/configuration/ui")
public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
}
@GetMapping("/swagger-resources")
public Mono<ResponseEntity> swaggerResources() {
return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
}
}
第二个文件:
package com.oracle.cloud.config;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.ArrayList;
import java.util.List;
/**
* @description:
* @author: dgl
* @time: 2020/10/20 13:37
*/
@Slf4j
@Component
@Primary
@AllArgsConstructor
public class SwaggerResourceConfig implements SwaggerResourcesProvider {
private final RouteLocator routeLocator;
private final GatewayProperties gatewayProperties;
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resources = new ArrayList<>();
List<String> routes = new ArrayList<>();
routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId())).forEach(route -> {
route.getPredicates().stream()
.filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
.forEach(predicateDefinition -> resources.add(swaggerResource(route.getId(),
predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
.replace("**", "v2/api-docs"))));
});
return resources;
}
private SwaggerResource swaggerResource(String name, String location) {
log.info("name:{},location:{}",name,location);
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion("2.0");
return swaggerResource;
}
}
4.在各个服务提供者(各个springboot项目)中加入以下依赖:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-micro-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>
5.在各个服务提供者(各个springboot项目)中加入以下配置:
package com.oracle.cloud.config;
import com.google.common.base.Predicates;
import io.swagger.annotations.ApiOperation;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import java.util.ArrayList;
@Configuration
@EnableSwagger2
//prefix+name通过application.yml文件配置是否启动swagger在线生成文档
@ConditionalOnProperty(prefix = "swagger", name = "open", havingValue = "true")
public class SwaggerConfig {
/**
* 创建获取api应用
*
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//这里采用包含注解的方式来确定要显示的接口(建议使用这种)
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.paths(Predicates.not(PathSelectors.regex("/error.*")))//错误路径不监控
.build();
}
/**
* 配置swagger文档显示的相关内容标识(信息会显示到swagger页面)
*
* @return
*/
private ApiInfo apiInfo() {
Contact contact = new Contact("xxxxx有限公司", "www.sss.com", "666666666@qq.com");
return new ApiInfo("xxx项目",
"xxx项目,此接口文档仅供内部查看",
"v1.0",
"www.xxx.com",
contact, "xxx执照",
"xxx执照URL",
new ArrayList<>()
);
}
}
6.在各个服务提供者(各个springboot项目)的controller层中加入以下注解(主要是与@Apixxx相关的注解):
package com.oracle.cloud.controller;
import com.oracle.cloud.common.ResultModel;
import com.oracle.cloud.model.MongoTest;
import com.oracle.cloud.model.SwaggerUser;
import com.oracle.cloud.service.MongoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
@Api(tags = {"测试服务-1"})
public class ProviderController {
@Autowired
private MongoService mongoService;
@GetMapping("/user")
@ApiOperation(value = "获取用户信息",notes = "测试用",response =SwaggerUser.class )
public SwaggerUser getUser( String name){
SwaggerUser swaggerUser = SwaggerUser.builder().headImgUrl("头像地址").mobile("13839312345").nickname("拉布拉多").username(name).sex(1).build();
return swaggerUser;
}
@GetMapping(value = "/insert/{id}/{age}/{name}")
@ApiOperation(value = "新增用户")
public ResultModel<MongoTest> insert(@PathVariable Integer id, @PathVariable Integer age, @PathVariable String name) {
return mongoService.insert(id,age,name);
}
}
7.最后在各个服务提供者(各个springboot项目)的yml文件中添加:
生产环境中不要设置成open,开发环境和本地环境设置成open
spring:
application:
name: cloud-provider-1 这里是各个服务提供者的服务名称
swagger:
open: true
8.运行顺序:
先运行各个服务提供者(各个springboot项目),最后运行网关gateway项目
效果如图: