您的位置:首页 > 编程语言 > Java开发

BES-SpringCloud Gateway网关整合多模块项目-Predicates与Filter

2020-02-17 04:45 501 查看

开发过程中使用了Spring Cloud Gateway来进行对各个服务的请求转发。

[code]spring:
application:
name: boss-bes-gateway
redis:
host: localhost
password: test123
port: 6379
main:
allow-bean-definition-overriding: true
cloud:
gateway:
discovery:
locator:
enabled: true
routes:
#        用户与权限管理
- id: boss-bes-user-permission-center
uri: http://localhost:10015/
predicates:
- Path=/boss-bes-user-permission-center/api/**
filters:
- StripPrefix=1
- name: Retry
args:
retries: 3
statuses: BAD_GATEWAY
- name: Hystrix
args:
name: fallbackcmd
fallbackUri: forward:/fallback
- name: RequestRateLimiter
args:
key-resolver: '#{@hostAddrKeyResolver}'
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 30
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 10000

以该yml中用户权限管理为例:

在没有用网关进行转发之前,请求的地址形式:

[code]localhost:10015/api/**

设置网关以后的请求的地址形式

[code]localhost:10003/boss-bes-user-permission-center/api/**

指定了uri(localhost:10015,要指向的地址)

对predicates指定了path(网关表现的地址)

filter配置StripPrefix=1的意思:把path的前1个路径截掉(/boss-bes-user-permission-center):

处理过后

前段发送以下请求:

localhost:10003/boss-bes-user-permission-center/api/**

网关:

1. 接收到/boss-bes-user-permission-center/api/**

2. 根据StripPrefix=1,截掉/boss-bes-user-permission-center,剩下api/**

3. 拼上uri=localhost:10015,得到localhost:10015/api/**,发送到后端。

 

Filter

网关中用到的filter有三种:熔断、限流、重试。

重试:参数为重试次数。

限流:根据IP限流。写一个限流类,并通过@Bean的方式注入

[code]public class HostAddrKeyResolver implements KeyResolver {
@Override
public Mono<String> resolve(ServerWebExchange exchange) {
return Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
}
}

//在Application类注入
@Bean
public HostAddrKeyResolver hostAddrKeyResolver() {
return new HostAddrKeyResolver();
}

yml文件中设置redis-rate-limiter.replenishRate(每秒最多几个请求)以及redis-rate-limiter.burstCapacity(每秒最多处理请求数),由于限流通过redis实现,因此redis需要进行配置。

熔断:其他服务通过feign调用此服务时,如果调用失败,则进入yml中设置的fallbackUri中。

(注意yml文件末尾设置了hystrix的超时时间,若调用进入等待超过设定时间就会触发熔断)

简单的熔断控制器:

[code]@RestController
public class FallbackController {

@PostMapping("/fallback")
public CommonResponse fallback() {
ResponseHead head = new ResponseHead();
head.setCode("HYSTRIX");
head.setMessage("服务熔断");
CommonResponse response = new CommonResponse();
response.setResponseHead(head);
return response;
}

@GetMapping("/fallback")
public CommonResponse fallback_get() {
ResponseHead head = new ResponseHead();
head.setCode("HYSTRIX");
head.setMessage("服务熔断");
CommonResponse response = new CommonResponse();
response.setResponseHead(head);
return response;
}
}

 

  • 点赞
  • 收藏
  • 分享
  • 文章举报
Tanker_97 发布了5 篇原创文章 · 获赞 0 · 访问量 367 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: