1、创建 eureka server 项目
使用intellij idea创建一个spring boot项目,创建服务中心。设置端口为5000。
修改配置文件,设置端口
server.port=5000
添加eureka-server依赖
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
2.0.1.RELEASE
Application.java添加注解@EnableEurekaServer
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
2、创建Eureka Client项目
分别新建两个 Spring Boot rest api接口服务 Customer、Product,分别设置端口号为9000和9001。
添加eureka-client依赖
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
2.0.1.RELEASE
修改Customer配置文件,设置端口号、应用名称及eureka服务的地址,如下:
server.port=9000
spring.application.name=CustomerService
eureka.client.service-url.defaultZone=http://localhost:5000/eureka
修改Product配置文件,设置端口号、应用名称及eureka服务的地址,如下:
server.port=9001
spring.application.name=ProductService
eureka.client.service-url.defaultZone=http://localhost:5000/eureka
分别对两个项目的Application.java添加注解@EnableDiscoveryClient
3、创建api网关
使用intellij idea创建一个spring boot项目,创建Api网关服务。设置端口为5555。
添加eureka-client和zuul依赖
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
2.0.1.RELEASE
org.springframework.cloud
spring-cloud-starter-netflix-zuul
2.0.1.RELEASE
修改配置文件,设置端口号、eureka服务的地址、应用名称及通过zuul.routes.名称.path和zuul.routes.名称.serviceId指定访问api服务对应的url路径
server.port=5555
eureka.client.service-url.defaultZone=http://localhost:5000/eureka
spring.application.name=ZuulGateway
zuul.routes.customers.path=/customers/**
zuul.routes.customers.service-id=CustomerService
zuul.routes.products.path=/products/**
zuul.routes.products.service-id=ProductService
注:service-id值必须与client项目配置文件中的spring.application.name值一致
Application.java添加@EnableDiscoveryClient和@EnableZuulProxy注解
@SpringBootApplication
@EnableZuulProxy
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
4、分别启动这4个应用,打开eureka服务:http://localhost:5000/
如下图所示全部注册成功:
eureka.png
打开http://localhost:5555/customers,返回结果如下:
image.png
打开http://localhost:5555/customers/10,返回结果如下:
image.png
打开http://localhost:5555/products,返回结果如下:
image.png
通过上面的例子说明Api网关服务已经生效。结合具体的业务场景,我们的生产环境只对外暴露5555端口,客户端访问Api网关,由Api网关去路由到各个服务节点,这样所有的客户端调用都统一了入口。