Zuul是一个Server端的路由器和过滤器,Zuul默认的会反向代理到所有注册到Eureka上的服务。
Zuul实现代理。
启动类
- package com.dynamic.cloud;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
- @SpringBootApplication
- @EnableZuulProxy
- public class ZuulApplication
- {
- public static void main( String[] args )
- {
- SpringApplication.run(ZuulApplication.class, args);
- }
- }
后面的代码中,启动类不会变化。
@EnableZuulProxy,是一个组合注解,@EnableCircuitBreaker,@EnableDiscoveryClient。因为它有@EnableDiscoveryClient,所以可以注册到Eureka上。
POM.xml中加入依赖
- <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>
- <artifactId>microservice-gateway-zuul</artifactId>
- <packaging>jar</packaging>
- <parent>
- <groupId>com.dynamic.cloud</groupId>
- <artifactId>microservice-spring-cloud</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- </parent>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- </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>
- </dependencies>
- </project>
- spring:
- application:
- name: microservice-gateway-zuul
- server:
- port: 8040
- eureka:
- client:
- service-url:
- defaultZone: http://user:pass123@localhost:8761/eureka #把Eureka註冊到那個Eureka
- instance:
- prefer-ip-address: true
- instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
- hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
- zuul:
- ignored-services: microservice-comsumer-movie-ribbon-withhystrix
- routes:
- microservice-provider-user: /user/**
zuul:
ignored-services: microservice-comsumer-movie-ribbon-withhystrix ,不允许代理本服务
routes:
microservice-provider-user: /user/** ,可以使用user替换microservice-provider-user访问路径。
只想反向代理一个微服务,不想反向代理其他的微服务
第一种:所有的服务都ignored,只有配置的才反向代理
第二种:在ignored上配置,不代理的服务。
启动Eureka,用户服务,Zuul服务
已经完成了简单的Zuul的实例
1.指定path+serviceid
- zuul:
- routes:
- abc: #让zuul方向代理微服务,路径是/user-path abc只要是唯一的就行,可随意写
- path: /user-path/** #封层匹配
- serviceId: microservice-provider-user
2.指定Path+url
- zuul:
- routes:
- abc: #让zuul方向代理微服务,路径是/user-path abc只要是唯一的就行,可随意写
- path: /user-path/** #封层匹配
- #serviceId: microservice-provider-user
- url: http://localhost:7900/
3.解决path + url 实现负载均衡
- zuul:
- routes:
- abc: #让zuul方向代理微服务,路径是/user-path abc只要是唯一的就行,可随意写
- path: /user-path/** #封层匹配
- serviceId: microservice-provider-user
- ribbon:
- eureka:
- enabled: false
- microservice-provider-user: #这是Ribbon要请求的微服务的ServiceId
- ribbon:
- listOfServers: http://localhost:7900,http://localhost:7901