一、简介
Zuul的作用就是路由转发和过滤, 即将请求转发到微服务或拦截请求; Zuul默认集成了负载均衡功能。
二、ZUUL配置
2.1、pom文件
<!-- zuul路由网关 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
2.2、yml
server:
port: 9527
spring:
application:
name: microservicecloud-zuul-gateway
eureka: #和eureka结合的
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
#,http://eureka7003.com:7003/eureka
instance:
instance-id: gateway-9527.com
prefer-ip-address: true
zuul:
#ignored-services: microservicecloud-dept
#prefix: /atguigu #统一前缀
ignored-services: "*" #忽略真是微服务名字
routes:
mydept: #自定义别名
serviceId: microservicecloud-dept #真是的微服务名称
path: /mydept/** #别名路径
info:
app.name: atguigu-microcloud
company.name: www.atguigu.com
build.artifactId: $project.artifactId$
build.version: $project.version$
2.3、启动类
package com.atguigu.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableZuulProxy
public class Zuul_9527_StartSpringCloudApp
{
public static void main(String[] args)
{
SpringApplication.run(Zuul_9527_StartSpringCloudApp.class, args);
}
}
2.4、访问
比如原来访问微服务是这样的
http://localhost:8001/dept/get/1 如果不配置 ignored-services: “*” (忽略真是微服务名字),那么可以这样访问http://localhost:9527/MICROSERVICECLOUD-DEPT/dept/get/1
其中9527是zuul的端口号
MICROSERVICECLOUD-DEPT是8001的微服务名字
如果想隐藏真正的微服务名字可以配置 ignored-services: “*”,然后给微服务配置其他别名路径比如
mydept: #自定义别名
serviceId: microservicecloud-dept #真是的微服务名称
path: /mydept/** #别名路径
然后我们就可以这样访问了
http://localhost:9527/mydept/dept/get/1
其中mydept是别名路径
三zuul结合ribbon
private static final String REST_URL_PREFIX = "http://MICROSERVICECLOUD-ZUUL-GATEWAY/mydept";
MICROSERVICECLOUD-ZUUL-GATEWAY:zuul微服务的名字,mydept是映射的具体消费者微服务的名字
三zuul结合feign
@FeignClient(value = "MICROSERVICECLOUD-ZUUL-GATEWAY/mydept",fallbackFactory=DeptClientServiceFallbackFactory.class)
基本上和相似。