本篇文章主要講解zuul路由的幾種基本配置的總結(jié)。
測(cè)試項(xiàng)目搭建
- 創(chuàng)建一個(gè)普通的下游服務(wù)client-a
核心代碼
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/add",method = RequestMethod.GET)
public String add(Integer id){
return "user:" + id;
}
}
配置文件
spring:
application:
name: client-a
server:
port: 8080
eureka:
client:
service-url:
defaultZone: http://eureka.springcloud.cn/eureka/
2.創(chuàng)建zuul-server服務(wù)
配置文件
spring:
application:
name: zuul-server
server:
port: 8888
eureka:
client:
service-url:
defaultZone: http://eureka.springcloud.cn/eureka/
zuul:
routes:
client-a:
path: /client/**
serviceId: client-a
3.接口測(cè)試
啟動(dòng)兩個(gè)服務(wù),用postman分別測(cè)試接口。
經(jīng)過(guò)zuul網(wǎng)關(guān)調(diào)取接口
由結(jié)果可知我們?cè)谡{(diào)取http://localhost:8888/client/user/add?id=1接口的時(shí)候,實(shí)際上是調(diào)用的http://localhost:8080/user/add?id=1接口。這是因?yàn)槲覀冊(cè)趜uul配置文件中指定了路由規(guī)則,當(dāng)想zuul server發(fā)起請(qǐng)求的時(shí)候,他就會(huì)去Eureka注冊(cè)中心拉取服務(wù)列表,如果發(fā)現(xiàn)有指定的路由映射規(guī)則,就會(huì)按照規(guī)則路由到相應(yīng)的接口上去。
Spring Cloud Zuul典型配置
1.單實(shí)例serviceId映射
zuul:
routes:
client-a:
path: /client/**
serviceId: client-a
上例中的配置,是一個(gè)/client/** 到client-a服務(wù)的映射規(guī)則,我們可以把它簡(jiǎn)化為一個(gè)較簡(jiǎn)單的配置
zuul:
routes:
client-a: /client/**
另外還有一種更加簡(jiǎn)單的映射規(guī)則,映射規(guī)則與serivceId都不用寫(xiě)
zuul:
routes:
client-a:
在這種情況下,Zuul會(huì)給client-a添加一個(gè)默認(rèn)的映射規(guī)則/client-a/**,相當(dāng)于:
zuul:
routes:
client-a:
path: /client-a/**
serviceId: client-a
這時(shí)候通過(guò)http://localhost:8888/client-a/user/add?id=1來(lái)調(diào)用。
2.單實(shí)例url映射
除了路由到服務(wù)外,還能路由到物理地址,將serviceId替換成url即可
zuul:
routes:
client-a:
path: /client/**
url: http://localhost:8080 #client-a的地址
3.多實(shí)例路由
在默認(rèn)情況下,zuul會(huì)使用Eureka中集成的基本負(fù)載均衡功能,如果想使用Ribbon的負(fù)載均衡功能,就需要指定一個(gè)serviceId,此操作需要禁止Ribbon使用Eureka,在E版之后新增了負(fù)載均衡的配置。
zuul:
routes:
client-a:
path: /client/**
serviceId: client-a
ribbon:
eureka:
enabled: false #禁止Ribbon使用Eureka
client-a:
ribbon:
NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
listOfServers: localhost:8080,localhost:8081
4.forward本地跳轉(zhuǎn)
有時(shí)候我們?cè)趜uul中會(huì)做一些邏輯處理,在網(wǎng)關(guān)(zuul server)中寫(xiě)好一個(gè)接口,如下所示
@RestController
public class TestController {
@RequestMapping(value = "/testMethod",method = RequestMethod.GET)
public String testMethod(Integer a){
return "本地跳轉(zhuǎn):"+a;
}
}
配置以下信息
zuul:
routes:
client-a:
path: /test/**
url: forward:/testMethod
調(diào)用http://localhost:8888/test?a=1接口返回如下
路由通配符
先介紹這么多,下次再介紹剩下的。