API 限流器(三) 在Spring Cloud 微服务体系中集成RedisRateLimiter

  这篇是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 Rate
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值