SpringCloud之使用Zuul配合Swagger生成API文档

动态网关的搭建https://blog.csdn.net/kxj19980524/article/details/87867026

在订单和会员服务上都引入swagger的依赖,配置文件加上扫包范围,然后controller里把需要写入api文档的方法上加上注解,最后在启动类上加上开启的注解就可以了,会员服务照做就可以了

        <!-- swagger-spring-boot -->
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.7.0.RELEASE</version>
        </dependency>

网关的搭建,首先也导入上面的依赖,在启动类多加这段配置

package com.buba;

import com.spring4all.swagger.EnableSwagger2Doc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
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;

@SpringBootApplication
@EnableEurekaClient
//开启注册网关
@EnableZuulProxy
@EnableSwagger2Doc
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    // zuul配置能够使用config实现实时更新
    @RefreshScope
    @ConfigurationProperties("zuul")
    public ZuulProperties zuulProperties() {
        return new ZuulProperties();
    }

    // 添加文档来源
    @Component
    @Primary
    class DocumentationConfig implements SwaggerResourcesProvider {
        @Override
        public List<SwaggerResource> get() {
            List resources = new ArrayList<>();
            // 第一个参数可以随便写, 第二个参数写网关上配置的访问服务的名称
            resources.add(swaggerResource("app-itmayiedu-member", "/member/v2/api-docs", "2.0"));
            resources.add(swaggerResource("app-itmayiedu-order", "/order/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;
        }
    }


}

上面方法中第一个参数就是在这个界面显示的名字,可以随便写

第二个参数是网关访问服务的第一段名称,这段配置放到码云上去了,我就在这方便截图

然后把网关上过滤器的判断条件先去掉,要不然测试麻烦还得拼接参数

配置好后启动eureka服务端,config服务端,order,member,zuul依次启动

访问的时候通过网关的端口进行访问swagger页面,网关端口我设置的是80所以不用加

猜你喜欢

转载自blog.csdn.net/kxj19980524/article/details/87889721