3.网关
spring cloud gatway = 服务统一管理(router)+ 请求过滤(filter)
1.使用
1.写pom
<!--discovery 服务发现注册-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<!--健康检查依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--getway 依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
2.写配置
方法1
server:
port: 8888
spring:
application:
name: GATWAY
cloud:
consul:
port: 8500
host: localhost
gateway:
routes:
#唯一标识
- id: emp
#服务地址
uri: http://localhost:8080
#断言
predicates:
- Path=/employee/**
filters:
- StripPrefix=1
- id: dep
uri: http://localhost:8081
predicates:
- Path=/department/**
filters:
- StripPrefix=1
方法二
public class GatewayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routesGatewayConfig()
.route("path_route", r -> r.path("/get")
.uri("http://httpbin.org"))
.route("host_route", r -> r.host("*.myhost.org")
.uri("http://httpbin.org"))
.route("rewrite_route", r -> r.host("*.rewrite.org")
.filters(f -> f.rewritePath("/foo/(?<segment>.*)", "/${segment}"))
.uri("http://httpbin.org"))
.route("hystrix_route", r -> r.host("*.hystrix.org")
.filters(f -> f.hystrix(c -> c.setName("slowcmd")))
.uri("http://httpbin.org"))
.route("hystrix_fallback_route", r -> r.host("*.hystrixfallback.org")
.filters(f -> f.hystrix(c -> c.setName("slowcmd").setFallbackUri("forward:/hystrixfallback")))
.uri("http://httpbin.org"))
.route("limit_route", r -> r
.host("*.limited.org").and().path("/anything/**")
.filters(f -> f.requestRateLimiter(c -> c.setRateLimiter(redisRateLimiter())))
.uri("http://httpbin.org"))
.build();
}
}
3.写注解
package com.wsz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class GetWayApplication {
public static void main(String[] args) {
SpringApplication.run(GetWayApplication.class,args);
}
}
gateway实现服务请求负载均衡
lb == load balance
server:
port: 8888
spring:
application:
name: GATWAY
cloud:
consul:
port: 8500
host: localhost
gateway:
routes:
#唯一标识
- id: emp
#服务路径
# uri: http://localhost:8080
#服务Id
uri: lb://EMPLOYEES
#断言
predicates:
- Path=/employee/**
filters:
- StripPrefix=1
- id: dep
#uri: http://localhost:8081
uri: lb://DEPARTMENTS
predicates:
- Path=/department/**
filters:
- StripPrefix=1
2.断言
predicates:
- Path=/employee/**
#在某段时间之后(ZonedDateTime.now())
- After=
#在某段时间之前
- Before=
#在某段时间之间
- Between=
#必须携带cookie<name,wsz>
- Cookie=name,wsz
#必须携带请求头Token
- Header=Token
#请求方式只能为GET
- Method=GET
3.过滤器
去除路径前1部分
- StripPrefix=1
#加前缀
- PrefixPath=/my
4.查看详细规则
management:
endpoints:
web:
exposure:
include: "*"