天天看點

SpringCloud學習筆記12zuul的四種路由-IDEA版

1.首先建立一個Module:

  • 選擇好依賴。
    SpringCloud學習筆記12zuul的四種路由-IDEA版
    2.在啟動引導類上加上啟用zuul元件的注解:
@EnableZuulProxy    //啟用zuul元件
           

3.配置application.yml檔案:

server:
  port: 10010
spring:
  application:
    name: itwei-zuul
zuul:
  routes:
    service-provider:   #路由名稱,可以随便寫,習慣上服務名
      path: /service-provider/**		#url上寫的路徑
      url: http://localhost:8082
           

4.然後就可以通過zuul網關來通路服務提供方的服務:

  • 服務提供方:
    SpringCloud學習筆記12zuul的四種路由-IDEA版
    但是這樣我們發現url都寫死了,是以我們要對zuul進行改造。

5.将zuul注入到eureka容器:

分三步:

  • 1.引入pom依賴:
<!-- 引入eureka依賴 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
           
  • 2.引導類上添加注解:
@EnableDiscoveryClient  //開啟eureka用戶端
           
  • 3.修改application.yml配置檔案:
server:
  port: 10010
spring:
  application:
    name: itwei-zuul
zuul:
  routes:
    service-provider:   #路由名稱,可以随便寫,習慣上服務名
      path: /service-provider/**    #url上寫的路徑
      #url: http://localhost:8082
      serviceId: service-provider   #eureka中服務名
      
eureka:     #配置要注入的eureka容器
  client:
    service-url:
      defaultZone: http://localhost:10086/eureka
           

4.最後運作代碼:

SpringCloud學習筆記12zuul的四種路由-IDEA版

5.可以簡化application.yml配置檔案:

server:
  port: 10010
spring:
  application:
    name: itwei-zuul
zuul:
  routes:
    service-provider: /service-provider/**  #路由名稱,可以随便寫,習慣上服務名

eureka:
  client:
    service-url:
      defaultZone: http://localhost:10086/eureka
           

6.最簡化application.yml配置檔案:

server:
  port: 10010
spring:
  application:
    name: itwei-zuul
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10086/eureka
           

預設直接根據注入到eureka容器中的服務名為url。

**server:

port: 10010

spring:

application:

name: itwei-zuul

zuul:

routes:

service-provider: /user/** #前面為注入到eureka的服務名,後面為輸入時添加的字首

service-consumer: /consumer/**

prefix: /api #統一再增加字首

eureka:

client:

service-url:

defaultZone: http://localhost:10086/eureka**

7.推薦還是需要配置一下滴:

server:
  port: 10010
spring:
  application:
    name: itwei-zuul

zuul:
  routes:
    service-provider: /user/**   #前面為注入到eureka的服務名,後面為輸入時添加的字首
    service-consumer: /consumer/**
  prefix: /api   #統一再增加字首
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10086/eureka
           

8.運作結果:

  • 服務提供方:
    SpringCloud學習筆記12zuul的四種路由-IDEA版
  • 服務調用方:
    SpringCloud學習筆記12zuul的四種路由-IDEA版