新建一个moudle
第一步引入依赖:
<?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"> <parent> <artifactId>cloud-demo</artifactId> <groupId>com.company</groupId> <version>1.0.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>zuul-gateway</artifactId> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency> </dependencies> </project>
第二步:写启动类,添加启用Zuul的注解@EnableZuulProxy
package com.company; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @SpringBootApplication
@EnableZuulProxy
@EnableDiscoveryClient
public class ZuulGatewayApplication { public static void main(String[] args) { SpringApplication.run(ZuulGatewayApplication.class); } }
第三步:配置application.yml
# 连接eureka注册中心 eureka: client: service-url: defaultZone: http://127.0.0.1:8888/eureka #指定端口 server: port: 8989 #配置当前服务名称 spring: application: name: zuul-gateway #配置网关
zuul网关有默认配置,就是匹配服务id,然后进行转发,并且实现了负载均衡
原本访问地址:http://localhost:8080/consumer3/1
加入zuul之后的访问地址:http://localhost:8989/consumer-service/consumer3/1
http://localhost:8989/服务id/consumer3/1
默认会从eureka中拉取服务列表,并生成默认路由映射。
#配置网关
zuul:
routes:
consumer-service: /consumer-service/** #等同于默认配置,此时eureka其他的服务也是这样的匹配规则
user-service: #如果想让单个服务的匹配缩短,可以单个配置,这样匹配成功后,转发时就不会去除前缀,访问路径:http://localhost:8989/user/1
path: /user/**
serviceId: user-service
strip-prefix: false
ignored-services: #配置要忽略的服务集合,这样zuul就不会生成该服务的默认映射,也就不会对外暴露该服务
- user-service #服务id
如果不想在zuul中暴露某些服务,可以添加如上配置