基于Spring Cloud Zuul方式

2019-05-30 20:55 更新

在基于nginx配置的環(huán)節(jié),其實我們已經(jīng)可以利用nginx的配置,幫助我們聚合文檔服務(wù)了,而通過代碼的方式該如何實現(xiàn)?

在Spring Cloud微服務(wù)架構(gòu)中,各個子服務(wù)都是分散的,每個服務(wù)集成了Swagger文檔,但是接口對接時需要單獨分別訪問,很麻煩,效率低下,

而Zuul可以幫助我們解決此難題,將多個微服務(wù)的Swagger接口聚合到一個文檔中,這樣整個微服務(wù)架構(gòu)下只會存在一個文檔出口,統(tǒng)一文檔口徑

本文檔只涉及如何整合Swagger及Zuul,其他相關(guān)知識點請自行搜索解決.

項目結(jié)構(gòu)

整個項目結(jié)構(gòu)如下:

swagger-bootstrap-ui-zuul
├── service-server -- eureka服務(wù)中心
├── service-order -- 微服務(wù)之一訂單服務(wù)模塊
├── service-user -- 微服務(wù)之一用戶服務(wù)模塊
├── service-doc -- 文檔中心,整合微服務(wù)Swagger文檔

eureka注冊服務(wù)中心以及微服務(wù)模塊Swagger的配置集成使用這里不過多驁述,和常規(guī)無異.

我們在eureka服務(wù)中心可以看到整個微服務(wù)模塊,如下圖:

微服務(wù)模塊

訂單、用戶兩個微服務(wù)模塊配置沒有什么區(qū)別,都是將自己的服務(wù)注冊到eureka中,并且每個微服務(wù)都集成Swagger的配置

@EnableEurekaClient
@SpringBootApplication
public class ServiceUserApplication {


    static Logger logger= LoggerFactory.getLogger(ServiceUserApplication.class);
    //...


}

此處需要注意的是Swagger的配置中,不需要設(shè)置groupName屬性

Swagger配置如下:



@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfiguration {


    @Bean(value = "userApi")
    @Order(value = 1)
    public Docket groupRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(groupApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xiaominfo.swagger.service.user.controller"))
                .paths(PathSelectors.any())


                .build().securityContexts(Lists.newArrayList(securityContext(),securityContext1())).securitySchemes(Lists.<SecurityScheme>newArrayList(apiKey(),apiKey1()));
    }


    private ApiInfo groupApiInfo(){
        return new ApiInfoBuilder()
                .title("swagger-bootstrap-ui很棒~~~?。?!")
                .description("<div style='font-size:14px;color:red;'>swagger-bootstrap-ui-demo RESTful APIs</div>")
                .termsOfServiceUrl("http://www.group.com/")
                .contact("group@qq.com")
                .version("1.0")
                .build();
    }






    private ApiKey apiKey() {
        return new ApiKey("BearerToken", "Authorization", "header");
    }
    private ApiKey apiKey1() {
        return new ApiKey("BearerToken1", "Authorization-x", "header");
    }


    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("/.*"))
                .build();
    }
    private SecurityContext securityContext1() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth1())
                .forPaths(PathSelectors.regex("/.*"))
                .build();
    }


    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Lists.newArrayList(new SecurityReference("BearerToken", authorizationScopes));
    }
    List<SecurityReference> defaultAuth1() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Lists.newArrayList(new SecurityReference("BearerToken1", authorizationScopes));
    }


}

文檔整合

service-doc模塊是最終整合user、order兩個微服務(wù)文檔的統(tǒng)一文檔出口,而本身也注冊到eureka服務(wù)中心中.

@EnableDiscoveryClient
@EnableEurekaClient
@EnableZuulProxy
@SpringBootApplication
public class ServiceDocApplication {


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


}

最后重寫SwaggerResource,代碼如下:

@Component
@Primary
public class SwaggerResourceConfig implements SwaggerResourcesProvider {


    Logger logger= LoggerFactory.getLogger(SwaggerResourceConfig.class);




    @Autowired
    RouteLocator routeLocator;


    @Override
    public List<SwaggerResource> get() {
        //獲取所有router
        List<SwaggerResource> resources = new ArrayList<>();
        List<Route> routes = routeLocator.getRoutes();
        logger.info("Route Size:{}",routes.size());
        for (Route route:routes) {
            resources.add(swaggerResource(route.getId(), route.getFullPath().replace("**", "v2/api-docs")));
        }
        return resources;
    }
    private SwaggerResource swaggerResource(String name, String location) {
        logger.info("name:{},location:{}",name,location);
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}

最終效果如下:

示例源碼

以上源碼可參考swagger-bootstrap-ui-demo中的子項目swagger-bootstrap-ui-zuul

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號