这篇是API限流器这个系列的终章,就是讲述如何在Spring Cloud 微服务开发中应用我发明的先进限流器。
本项目的代码地址为:https://github.com/tangaiyun/spring-cloud-microservice-ratelimiter
限流器的代码地址为:https://github.com/tangaiyun/RedisRateLimiter
开篇明义,基本思路如下:
1. 定义一个annotation - RedisLimiter
2. 在RestController 中有URL Mapping 的方法上应用RedisLimiter注解
3. 定义一个拦截器 - RateLimitCheckInterceptor,继承org.springframework.web.servlet.HandlerInterceptor
4. 定义一个WebMvcConfigurerAdapter,把上面的RateLimitCheckInterceptor启用,拦截所有的URL请求
5. 定义一个RedisRateLimiterFactory,这个工厂对RedisLimiter对象做了一些缓存。
项目的整个代码结构如图所示:
基本的调用时序图如下:
下面我将就一些重要的类和配置逐一讲解:
1. 首先是application.yml
这个文件是Spring Cloud 微服务的重点配置文件,内容为:
server:
port: 8080 #微服务端口
spring:
application:
name: ratelimitersample #微服务名称
jpa: #JPA的配置信息
generate-ddl: false
show-sql: true
hibernate:
ddl-auto: none
datasource: # 指定数据源
platform: h2 # 指定数据源类型
schema: classpath:schema.sql # 指定h2数据库的建表脚本
data: classpath:data.sql # 指定h2数据库的数据脚本
redis: # Redis配置信息
host: 192.168.0.135
port: 6379
password: foobared
timeout: 2000
pool: #Jedis Pool的配置信息
maxIdle: 300
minIdle: 100
max-wait: -1
max-active: 600
logging: # 配置日志级别,让hibernate打印出执行的SQL
level:
root: INFO
org.hibernate: INFO
org.hibernate.type.descriptor.sql.BasicBinder: TRACE
org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
eureka: #eureka的配置信息
client:
healthcheck: #打开服务健康检查
enabled: true
serviceUrl:
defaultZone: http://192.168.0.118:8761/eureka/
instance: #服务实例细信息
app-group-name: product
prefer-ip-address: true
instance-id: ${spring.application.name}:${server.port}
lease-expiration-duration-in-seconds: 10
lease-renewal-interval-in-seconds: 5
2. RateLimiter自定义annotation
package com.tay.ratelimitersample.ratelimiter;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;
@Retention(RUNTIME)
@Target({ TYPE, METHOD })
public @interface RateLimiter {
public enum Base {
General, //统一控制
IP, //按IP限制
User //按用户控制
};
Base