稀土 2017-12-12
spring-cloud-zuul-ratelimit是和zuul整合提供分布式限流策略的扩展,只需在yaml中配置几行配置,就可使应用支持限流
<dependency>
<groupId>com.marcosbarbero.cloud</groupId>
<artifactId>spring-cloud-zuul-ratelimit</artifactId>
<version>1.3.4.RELEASE</version>
</dependency>服务粒度 (默认配置,当前服务模块的限流控制)
用户粒度 (详细说明,见文末总结)
ORIGIN粒度 (用户请求的origin作为粒度控制)
接口粒度 (请求接口的地址作为粒度控制)
以上粒度自由组合,又可以支持多种情况。
如果还不够,自定义RateLimitKeyGenerator实现。
//默认实现
public String key(final HttpServletRequest request, final Route route, final RateLimitProperties.Policy policy) {
final List<Type> types = policy.getType();
final StringJoiner joiner = new StringJoiner(":");
joiner.add(properties.getKeyPrefix());
if (route != null) {
joiner.add(route.getId());
}
if (!types.isEmpty()) {
if (types.contains(Type.URL) && route != null) {
joiner.add(route.getPath());
}
if (types.contains(Type.ORIGIN)) {
joiner.add(getRemoteAddr(request));
}
// 这个结合文末总结。
if (types.contains(Type.USER)) {
joiner.add(request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : ANONYMOUS_USER);
}
}
return joiner.toString();
}
zuul:
ratelimit:
key-prefix: your-prefix
enabled: true
repository: REDIS
behind-proxy: true
policies:
myServiceId:
limit: 10
quota: 20
refresh-interval: 30
type:
- user以上配置意思是:30秒内允许10个访问,并且要求总请求时间小于20秒
yaml配置:
zuul:
ratelimit:
key-prefix: pig-ratelimite
enabled: true
repository: REDIS
behind-proxy: true
policies:
pig-admin-service:
limit: 2
quota: 1
refresh-interval: 3动态图 ↓↓↓↓↓

Redis 中数据结构 注意红色字体

2、架构图zuul 像其他微服务一样作为一个微服务向eureka server注册,并且能够通过注册列表获取所有的可用服务,其内部默认实现了ribbon,可达到负载均衡的目的,此时的微服务架构图如下: