本文共 4370 字,大约阅读时间需要 14 分钟。
Zuul 是Netflix 旗下实现路由网关的一个组件,客户端在进行请求时,首先请求会到达网关,然后网关将请求分发到不同的服务,网关可以根据 URI 区别用户请求的具体服务,然后进行转发,返回响应的资源给用户。
创建 maven 工程,添加核心的父 maven 依赖,所有子 pom 文件继承这个父 pom 文件。
UTF-8 1.8 1.8 Finchley.RELEASE org.springframework.boot spring-boot-starter-parent 2.0.5.RELEASE junit junit 4.11 test org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import
添加 maven 依赖
com.hly 05-spring-cloud-zuul 1.0-SNAPSHOT UTF-8 UTF-8 1.8 org.springframework.cloud spring-cloud-starter-netflix-eureka-server org.springframework.boot spring-boot-starter-web
application.yml 配置文件
server: port: 8761eureka: instance: hostname: localhost client: registerWithEureka: false fetchRegistry: false serviceUrl: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/spring: application: name: service-server
SpringBoot 启动类
@SpringBootApplication@EnableEurekaServerpublic class ServiceServerApplication { public static void main(String[] args) { SpringApplication.run(ServiceServerApplication.class, args); }}
两个客户端的配置代码基本一致,这里以一个为例
添加 maven 依赖
com.hly 05-spring-cloud-zuul 1.0-SNAPSHOT UTF-8 UTF-8 1.8 org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.boot spring-boot-starter-web
application.yml 配置文件
server: port: 8762spring: application: name: service-client-helloeureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/
SpringBoot 启动类
@SpringBootApplication@RestController@EnableEurekaClientpublic class ServiceClientHelloApplication { public static void main(String[] args) { SpringApplication.run(ServiceClientHelloApplication.class, args); } @Value("${server.port}") String port; @RequestMapping("/hello") public String home(@RequestParam(value = "name",defaultValue = "hly") String name){ return "hello "+name+",I am from port: " + port; }}
添加 maven 依赖
com.hly 05-spring-cloud-zuul 1.0-SNAPSHOT UTF-8 UTF-8 1.8 org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-zuul
application.yml 配置文件
eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/server: port: 8769spring: application: name: service-zuulzuul: routes: api-hello: path: /api-hello/** serviceId: service-client-hi api-hi: path: /api-hi/** serviceId: service-client-hello
SpringBoot 启动类
@SpringBootApplication@EnableEurekaServerpublic class ServiceServerApplication { public static void main(String[] args) { SpringApplication.run(ServiceServerApplication.class, args); }}
1、首先启动注册中心
2、然后启动两个客户端 3、启动路由网关 4、访问 http://localhost:8769/api-hello/hello 路由到 hello 客户端 5、访问 http://localhost:8769/api-hi/hi 路由到 hi 客户端05-spring-cloud-zuul:
我的 Github:
CSDN: 个人网站: E-mail: 1136513099@qq.com
推荐阅读
转载地址:http://tufsi.baihongyu.com/