图5-12展现了一个适应当前架构的API Gateway。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.xc</groupId> <artifactId>xcservice-springcloud</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <groupId>com.xc</groupId> <artifactId>xcservice-gateway-zuul</artifactId> <version>0.0.1-SNAPSHOT</version> <name>xcservice-gateway-zuul</name> <description>网关服务</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
(2)编辑配置文件。在配置文件中编写Eureka服务实例的端口号、服务端地址等信息,如文件5-9所示。
server:
port: 8050 # 指定该Eureka实例的端口号
eureka:
instance:
prefer-ip-address: true # 是否显示主机的IP
#instance-id: ${spring.cloud.client.ipAddress}:${server.port} #将Status中的显示内容也以“IP:端口号”的形式显示
client:
service-url:
defaultZone: http://localhost:8761/eureka/ # 指定Eureka服务端地址
spring:
application:
name: xcservice-gateway-zuul # 指定应用名称
zuul:
routes:
order-serviceId: # zuul的惟一标识
path: /order/** # 须要映射的路径
service-id: xcservice-eureka-order # Eureka中的serviceId
在上述配置信息中,zuul就是API网关服务的路由配置。其中order-serviceId为Zuul的惟一标识,能够任意设置名称,但必须惟一,若是该值与service-id的名称相同时,service-id的值能够省略。path属性后面的值表示须要映射的路径,service-id后面的值为Eureka中的serviceId,应用在运行时,全部符合映射路径的URL都会被转发到xcservice-eureka-order中。java
须要注意的是,Zuul的配置方式有不少,这里只是针对本案例实现的一种方式。若是读者想要了解更多的配置方式,能够参考官方文档中Zuul的配置进一步学习。spring
package com.xc.xcservicegatewayzuul; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; /** * http://localhost:8050/xcservice-eureka-order/order/1 */ @EnableZuulProxy @SpringBootApplication @EnableEurekaClient public class XcserviceGatewayZuulApplication { public static void main(String[] args) { SpringApplication.run(XcserviceGatewayZuulApplication.class, args); } }
(4)分别启动注册中心、服务提供者和网关服务后,注册中心已注册的服务如图5-13所示。