网关可以将服务和外网进行隔离起到一定的保护作用,同时服务间局域网通信更加便捷。而且在网关中可以做到限流,权限校验,使得服务更加专注自身的业务。比如说下单需要登录权限。
spring cloud Gateway 工作原理
客户端向spring cloud Gateway发送请求,如果请求与网关程序定义的路由匹配,则将其发送到网关web处理程序,此处理程序运行特定的请求过滤链
过滤器之间用虚线分开的原因是过滤器可能会在发送代理请求之前或者之后执行逻辑。所有"pre"过滤器先执行,然后执行代理请求,代理请求完成后,执行post 过滤器逻辑。
项目构成
项目 端口 描述
gateway-eureka-server 8080 服务注册与发现
gateway-service 8081 服务
gateway-client 8082 网关 gateway
gateway-eureka-server
pom文件
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.2.RELEASE
com.taotao
eureka-server
0.0.1-SNAPSHOT
eureka-server
Demo project for Spring Boot
1.8
Greenwich.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
spring-milestones
Spring Milestones
https://repo.spring.io/milestone
启动项
@EnableEurekaServer
@SpringBootApplication
public class GatewayEurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
配置文件 application.yml
spring:
application:
name: gateway-eureka-server
server:
port: 8080
eureka:
instance:
hostname: localhostname
client:
fetch-registry: false
register-with-eureka: false
service-url:
defaultZone: http://localhost:8080/eureka/
访问http://localhost:8080 注册中心
gateway-service 项目
pom文件,
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.2.RELEASE
com.taotao
service-one
0.0.1-SNAPSHOT
service-one
Demo project for Spring Boot
1.8
Greenwich.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-config
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
spring-milestones
Spring Milestones
https://repo.spring.io/milestone
启动类
@EnableEurekaClient
@SpringBootApplication
public class GatewayServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceOneApplication.class, args);
}
}
配置文件 application.yml
spring:
application:
name: gateway-service
server:
port: 8081
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka/
创建类控制器 HelloWorldController ,http://localhost:8081/user/who
@RequestMapping("/user")
@RestController
public class HelloWorldController{
@RequestMapping("who")
public String helloworld() {
return "my name is liangwang";
}
}
创建类控制器OrderController, http://localhost:8081/order/info
@RequestMapping("/order")
@RestController
public class OrderController {
@RequestMapping("/info")
public String orderInfo() {
return "order info date : " + new Date().toString();
}
}
gateway-client项目
pom文件
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.2.RELEASE
com.taotao
gateway-client
0.0.1-SNAPSHOT
gateway-client
Demo project for Spring Boot
1.8
Greenwich.RELEASE
org.springframework.cloud
spring-cloud-starter-gateway
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
spring-milestones
Spring Milestones
https://repo.spring.io/milestone
使用RouteLocator的Bean进行路由转发,将请求进行处理,最后转发到目标的下游服务
@SpringBootApplication
public class GatewayClientApplication {
@Value("${test.uri}")
private String uri;
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
//basic proxy
.route(r -> r.path("/order/**")
.uri(uri)
).build();
}
public static void main(String[] args) {
SpringApplication.run(GatewayClientApplication.class, args);
}
}
上面的代码里是访问http://localhost:8083/order/的时候,网关转发到
http://gateway-service:8081/order/, gateway-service服务在eureka中有注册,最终对应的ip: port
使用配置文件
application.yml
test:
uri: lb://gateway-service
spring:
application:
name: gateway-client
cloud:
gateway:
routes:
- id: route_service_one
uri: ${test.uri} # uri以lb://开头(lb代表从注册中心获取服务),后面接的就是你需要转发到的服务名称
predicates:
- Path=/user/**
server:
port: 8083
logging:
level:
org.springframework.cloud.gateway: TRACE
org.springframework.http.server.reactive: DEBUG
org.springframework.web.reactive: DEBUG
reactor.ipc.netty: DEBUG
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka/
instance:
prefer-ip-address: true
其中test.uri是自我定义的属性: uri以lb://开头(lb代表从注册中心获取服务),后面接的就是你需要转发到的服务名称,按照上面的配置是http://localhost:8083/user/** => http://gateway-service:8081/user/** 到此项目搭建完成,接下来进行测试,依次启动gateway-eureka-server ,gateway-service, gateway-client
访问;
- http://localhost:8083/user/who
- http://localhost:8083/order/info
不启用注册中心
即使集成了eureka-client也可以不使用注册中心,可以关闭
eureka.client.enabled=false
StripPreffix属性的使用
按照上面的配置,每一个路由只能对应有个控制器的转发,不够灵活,假如想让userapi的请求都转发到gateway-service 服务,比如:
- http://localhost:8083/userapi/user/who => http://localhost:8081/user/who* http://localhost:8083/userapi/order/info => http://localhost:8081/order/info
在路由配置上增加 stripPrefix=1
spring:
application:
name: gateway-client
cloud:
gateway:
routes:
- id: route_service_one
uri: ${test.uri} # uri以lb://开头(lb代表从注册中心获取服务),后面接的就是你需要转发到的服务名称
predicates:
- Path=/userapi/** #userapi
filters:
- StripPrefix=1 # 表示在转发时去掉userapi
修改完配置,重启:
使用Hystrix
在gateway-client项目中引入依赖
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
在spring cloud gateway中可以使用hystrix。Hystrix 是spring cloud 中一个服务熔断降级的组件,在微服务系统有着十分重要的作用。
Hystrix是 spring cloud gateway中是以filter的形式使用的,代码如下:
@SpringBootApplication
public class GatewayClientApplication {
@Value("${test.uri}")
private String uri;
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
//basic proxy
.route(r -> r.path("/order/**")
.uri(uri)
)
.route(r -> r.path("/user/**")
.filters(f -> f
.hystrix(config -> config
.setName("myserviceOne")
.setFallbackUri("forward:/user/fallback")))
.uri(uri)).build();
}
public static void main(String[] args) {
SpringApplication.run(GatewayClientApplication.class, args);
}
}
上面代码中添加了一个路由并配置了hystrix的fallbackUri,新增加一个FallbackController控制器
@RestController
public class FallBackController {
@RequestMapping("/user/fallback")
public Mono fallback() {
return Mono.just("service error, jump fallback");
}
}
重启gateway-client项目,并关闭service-one服务,在浏览器访问
http://localhost:8083/user/who
使用yml 配置Hystrix
spring:
application:
name: gateway-client
cloud:
gateway:
routes:
- id: route_service_one
uri: ${test.uri} # uri以lb://开头(lb代表从注册中心获取服务),后面接的就是你需要转发到的服务名称
predicates:
- Path=/userapi/**
filters:
- StripPrefix=1 # 表示在转发时去掉userapi
- id: userapi2_route
uri: ${test.uri}
predicates:
- Path=/userapi2/**
filters:
- StripPrefix=1
- name: Hystrix
args:
name: myfallbackcmd
fallbackUri: forward:/user/fallback
在配置中增加了一个新的路由userapi2_route,还配置了Hystrix,当发生错误时会转发到 fallbackUri, 测试访问 http://localhost:8083/userapi2/order/info
reference
Hystrix wiki
Spring Cloud Gateway
Redis RateLimiter
转载Redis RateLimiter实现
转载Spring Cloud Gateway 基础使用