1. 程式人生 > >Spring Cloud學習筆記19——如何整合 Zuul

Spring Cloud學習筆記19——如何整合 Zuul

Zuul的功能

在這裡插入圖片描述

整合Zuul

開發環境

  • JDK8+
  • Gradle4+
  • Redis 3.2.100
  • Spring Boot 2.0.0.M3
  • Spring Cloud Starter Netflix Eureka Client Finchley.M2
  • Spring Cloud Starter Netflix Zuul Finchley.M2

建立專案

以之前的micro-weather-eureka-client為藍本,建立micro-weather-eureka-client-zuul專案
在這裡插入圖片描述

修改原始碼

修改build.gradle

配置,新增Zuul依賴:

//依賴關係
dependencies {

    //Eureka Client
    compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')

    //Zuul
    compile('org.springframework.cloud:spring-cloud-starter-netflix-zuul')

    //該依賴用於測試階段
    testCompile('org.springframework.boot:spring-boot-starter-test'
) }

修改com.study.spring.cloud.weather包下的Application類,加入@EnableZuulProxy註解:

package com.study.spring.cloud.weather;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

/*
 * @SpringBootApplication註解宣告Spring Boot應用
 * 作用等同於@Configuration, @EnableAutoConfiguration, @ComponentScan,
 * 簡化Spring配置
*/
@SpringBootApplication
//啟用可發現的客戶端
@EnableDiscoveryClient
//啟用Zuul的代理功能
@EnableZuulProxy
//Application類一定要處於整個工程的根目錄下,這樣它才能根據配置去掃描子節點下的Spring的Bean
public class Application {

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

修改application.properties配置檔案:

#應用名稱
spring.application.name=micro-weather-eureka-client-zuul

#註冊伺服器的URL
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/

#zuul本身的配置
#設定需要路由的URL,此處設定hi資源的路徑
zuul.routes.hi.path=/hi/**
#訪問hi應用時將請求轉發到某應用的應用名稱
zuul.routes.hi.service-id=micro-weather-eureka-client

執行

先通過IDE執行micro-weather-eureka-server

再通過命令列編譯、執行micro-weather-eureka-client,注意指定執行埠(如8081),完成後可訪問http://localhost:8081/hello頁面:
在這裡插入圖片描述

最後通過IDE執行micro-weather-eureka-client-zuul,執行結果如下:
在這裡插入圖片描述
訪問http://localhost:8080/hello頁面:
在這裡插入圖片描述
訪問http://localhost:8080/hi/hello頁面:
在這裡插入圖片描述