SpringCloudGateway整合knife4j在线api文档

整合官网: (点击打开)

1.User用户微服改造

1.1 添加依赖

	<!--knife4j-micro-包含swagger2依赖-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-micro-spring-boot-starter</artifactId>
            <version>2.0.2</version>
        </dependency>

1.2 编写Swagger2Config


@Configuration
@EnableSwagger2
@EnableKnife4j
public class Swagger2Config {
    
	/**
     * 创建RestApi 并包扫描controller
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())// 对所有api进行监控
                .paths(PathSelectors.any())
            	 //不显示错误的接口地址
                .paths(Predicates.not(PathSelectors.regex("/error.*")))//错误路径不监控
                .build();
    }
    
	/**
     * 创建Swagger页面 信息
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("用户微服")
                .description("用户微服")
                .version("1.0.0-SNAPSHOT")
                .build();
    }
}

1.3 application配置文件加上,开启生产环境不启用文档

#生产环境,屏蔽文档接口(默认false)
knife4j.production=${knife4j}

1.4 接口注解编写

@RestController
@Api(tags = "用户管理",value = "获取用户信息")
public class WebController {
	
	@Autowired
	private OrderFeignService orderFeignService;

	@ApiOperation(value = "用户查询", notes = "获取测试",response = String.class)
	@ApiImplicitParams({@ApiImplicitParam(name = "name", value = "用户名", dataType = "STRING", paramType = "QUERY", defaultValue = "lilei",required = true)})
	@GetMapping(value = "/hi")
	public String hi(String name){
		String id = orderFeignService.findId(name);
		return id;
	}

	@ApiOperation(value = "MemberVip查询", notes = "获取MemberVip测试",response = MemberVip.class)
	@GetMapping(value = "/hello")
	public MemberVip hello(){
		MemberVip memberVip = new MemberVip();
		memberVip.setId("123456");
		memberVip.setMemberId("654321");
		memberVip.setUsedNubmer(888);
		memberVip.setLimitNumber(666);
		memberVip.setExpiredNumber(999);
		memberVip.setVipLevel(100);
		return memberVip;
	}
}

1.5 实体类注解编写

public class MemberVip implements Serializable {

    private static final long serialVersionUID=1L;

    @ApiModelProperty(value = "主键")
    private String id;

    @ApiModelProperty(value = "用户ID")
    private String memberId;
    ......
 }

2. spring-cloud-starter-gateway网关整合所有微服api

2.1 添加依赖

	<!--knife4j依赖-->
		<dependency>
			<groupId>com.github.xiaoymin</groupId>
			<artifactId>knife4j-spring-boot-starter</artifactId>
			<version>2.0.2</version>
		</dependency>

2.2编写配置类

@Configuration
@Primary  //代表是Swagger主 配置
public class DocumentationConfig implements SwaggerResourcesProvider {

    public static final String API_URI = "v2/api-docs";
    private final RouteLocator routeLocator;
    private final GatewayProperties gatewayProperties;

    public DocumentationConfig(RouteLocator routeLocator, GatewayProperties gatewayProperties) {
        this.routeLocator = routeLocator;
        this.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("**", API_URI))));
        });
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("1.0");
        return swaggerResource;
    }
}

2.3 编写SwaggerHandler获取api接口信息

/**
 * 获取api接口信息
 */
@RestController
@RequestMapping("/swagger-resources")
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("/configuration/security")
    public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
        return Mono.just(new ResponseEntity<>(
                Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));

    }

    @GetMapping("/configuration/ui")
    public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
        return Mono.just(new ResponseEntity<>(
                Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
    }

    @GetMapping("")
    public Mono<ResponseEntity> swaggerResources() {
        Mono<ResponseEntity> just = Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
        return just;
    }
}

2.4 启动配置

最后,项目启动类添加相关注解,代码如下:

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient

注意点

在集成Spring Cloud Gateway网关的时候,会出现没有basePath的情况(即定义的例如/user、/order等微服务的前缀),这个情况在使用zuul网关的时候不会出现此问题,因此,在Gateway网关需要添加一个Filter实体Bean

解决看官网。

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐