gateway閘道器小demo
阿新 • • 發佈:2021-01-16
zuul1.x系列作為閘道器,基於servlet實現,屬於多執行緒同步阻塞模型;zuul2.x改寫netty,屬於非同步非阻塞模型;gateway屬於非同步非阻塞模型。
這裡基於spring-session+redis+zuul session共享示例,將其中的zuul閘道器替換為gateway閘道器技術。
工程改造
pom依賴
引入gateway依賴包
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
增加eureka註冊中心依賴資訊,這裡不能使用spring-cloud-starter-netflix-eureka-server,與gateway的jar包有衝突,可以參考Consider defining a bean of type ‘org.springframework.http.codec.ServerCodecConfigurer‘ in your conf
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
程式碼啟動類
註解該類為一個springboot工程,並且通過@EnableDiscoveryClient將其註冊到註冊中心
@EnableDiscoveryClient
@SpringBootApplication
public class Gateway {
public static void main(String[] args) {
SpringApplication.run(Gateway.class, args);
}
}
配置檔案
server: port: 5000 #gateway閘道器服務埠號 spring: application: name: gateway #gateway閘道器例項名稱 cloud: gateway: discovery: locator: enabled: true lowerCaseServiceId: true #請求url是否大小寫敏感,預設false敏感;true表示不敏感 routes: #路由資訊配置 - id: um_route #一個id為一組路由資訊 uri: lb://um #將請求路由到um服務 predicates: #請求格式 - Path=/um/** - id: bm_route uri: lb://bm predicates: - Path=/bm/** management: endpoints: web: exposure: include: '*' #暴露所有端點資訊給actuator eureka: # eureka服務註冊中心資訊 instance: prefer-ip-address: true client: service-url: defaultZone: http://localhost:8761/eureka
專案測試
依次啟動 servicecenter、gateway、UserManagerA、UserManagerB 和 BuyManager工程,啟動完畢後,開啟註冊中心http://localhost:8761/可以看到各例項註冊成功
功能測試易正常。
至此,一個簡單的gateway小demo完成。