springcloud+zuul+swagger2之微服務通過網關進行分發


因公司技術架構需要,我從zk+dubbo+springboot開始接觸springcloud一系列架構。首先接觸到新東西,我內心是希望得到學習的,畢竟技多不壓身,更何況用springcloud也不是新技術了[苦瓜臉]。此文章主要講述整個配置關鍵點,其他細節請找我家彥宏。

進入正題:用zuul網關的目的,就我目前來看是為了讓幾個服務對外保證一個域名請求,得到請求后網關進行轉發到各個服務上。第一步准備兩個及以上的微服務,這些都是注冊到eureka上的服務名稱

 1.user-serive

     user-service服務里的controller1: api/v1/user/userAddress

                                       controller2:api/v1/user/userCompany

 2.order-service:如上

 3.zuul-service(網關服務)

 第二步,在zuul服務里配置轉發策略:

  創建zuul模塊的功能,就忽略不講了,都可以在網上搜到。主要是一些配置application.yml的地方,我粘貼出來:

zuul:
  routes:
    order-service:
      path: /**/order/** 此處一定要這樣寫,不要寫成/order/**;否則在進行轉發的時候,請求不通;會在轉發的時候,前面需要手動加上order,再連接api/v1才能請求;
    user-service:
      path: /**/user/**

 在請求轉發的過程中,第一次請求的時候,zuul會超時,原因如下:(如果大家想仔細了解,可去深究zuul機制)

這是因為zuul采用了懶加載機制,第一次訪問的時候才會加載某些類,而不是啟動時就加載了,由於默認的時間原本就比較短,加載這些類又需要一些時間,這就造成超時了。

解決方式是在application.yml中配置:

zuul:
host:(跟以上routes同等級) connect-timeout-millis: 15000 #HTTP連接超時大於Hystrix的超時時間 socket-timeout-millis: 60000 #socket超時
ribbon: (跟zuul同等級)       #設置ribbon的超時時間小於zuul的超時時間
  ReadTimeout: 10000
  ConnectTimeout: 10000

  此時,如果有請求地址中有order的,就會轉發到order-service去請求;如果地址中有user的,則會轉發到user-service請求,成功轉發。

 

————————————————————————————————————————————————————————

接下來貼一下swagger關聯代碼

添加swagger的方式:

1.在zuul服務中pom.xml加入:

<!-- swagger2 依賴 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.0</version> </dependency> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.8.1</version> </dependency>

2.新建swagger配置類:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Autowired
    private DiscoveryClientRouteLocator discoveryClientRouteLocator;
    @Bean
    public Docket buildDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(buildApiInfo()) // .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo buildApiInfo() {
        return new ApiInfoBuilder()
                .title("對接接口文檔")
                .description("相關后台接口")
                .contact("程序猿")
                .version("1.0")
                .build();
    }

 3.新建文檔配置類

@Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider{

    private final RouteLocator routeLocator;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${spring.application.name}")
    private String applicationName;

    public DocumentationConfig(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }
   // 自動獲取系統配置的路由資源集合
   @Override
   public List<SwaggerResource> get() { List<SwaggerResource> resources = new ArrayList<>(); // 排除自身,將其他的服務添加進去 discoveryClient.getServices().stream().filter(s -> !s.equals(applicationName)).forEach(name -> { Optional<ServiceInstance> instanceOptional = discoveryClient.getInstances(name).stream().findFirst(); if (instanceOptional.isPresent() && instanceOptional.get().getMetadata().containsKey("context-path")) { String contexPath = instanceOptional.get().getMetadata().get("context-path"); resources.add(swaggerResource(name, "/" + name + contexPath + "/v2/api-docs", "2.0")); } else { resources.add(swaggerResource(name, "/" + name + "/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; } } 

————————————————————————————————————————————————————————

最后整體效果為:

 

注明:

此文章純屬個人分享,如有不對的地方請大家批評指正。

解決出來的部分內容也是我在網上搜羅匯集的,僅供參考 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM