新增AI编程课程,引领技术教育新趋势
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- zuul --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency> <!-- eureka --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <!-- 热启动,热部署依赖包,为了调试方便,加入此包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <!-- spring cloud dependencies --> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Edgware.SR3</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
(2)启动类添加@EnableZuulProxy注解
@SpringBootApplication @EnableZuulProxy public class ZuulServiceApplication { public static void main(String[] args) { SpringApplication.run(ZuulServiceApplication.class, args); } }
(3)添加必要配置(application.yml):主要是针对Eureka的配置,本示例将Zuul也作为一个Eureka Client注册到Eureka Server中。
server: port: 5000 spring: application: name: zuul-gateway-service eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ instance: prefer-ip-address: true # 优先注册IP地址而不是hostname instance-id: zuul-gateway-container:${server.port} healthcheck: enabled: true # 启用健康检查,注意:需要引用spring boot actuator management: security: enabled: false # 默认为true,改为false以便可以看到routes
启动Eureka Server和Zuul Server之后:

示例代码:https://github.com/EdisonChou/Microservice.PoC.Steeltoe/tree/master/springcloud/zuul-service
基于第一篇的三个已注册到Eureka的ASP.NET Core WebAPI示例项目(示例代码:https://github.com/EdisonChou/Microservice.PoC.Steeltoe/tree/master/src/Chapter1-ServiceDiscovery),无须做任何修改,启动并注册到Eureka之后的服务列表:

(1)通过Zuul访问Agent-Service

(2)通过Zuul访问Premium-Service
