Class SmsRateLimiter

java.lang.Object
cloud.opencode.base.sms.validation.SmsRateLimiter
All Implemented Interfaces:
AutoCloseable

public final class SmsRateLimiter extends Object implements AutoCloseable
SMS Rate Limiter 短信频率限制器

Prevents SMS abuse by limiting send frequency.

通过限制发送频率防止短信滥用。

Features | 主要功能:

  • Per-minute, per-hour, per-day rate limits - 每分钟、每小时、每天限制
  • Automatic record cleanup - 自动记录清理
  • AutoCloseable for resource cleanup - AutoCloseable资源清理

Usage Examples | 使用示例:

try (SmsRateLimiter limiter = new SmsRateLimiter(1, 5, 10)) {
    limiter.checkAndRecord("13800138000"); // throws SmsRateLimitException if exceeded
}

Security | 安全性:

  • Thread-safe: Yes (ConcurrentHashMap + atomic operations) - 线程安全: 是(ConcurrentHashMap + 原子操作)
Since:
JDK 25, opencode-base-sms V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Constructor Details

    • SmsRateLimiter

      public SmsRateLimiter()
      Create rate limiter with defaults 使用默认值创建限流器
    • SmsRateLimiter

      public SmsRateLimiter(int limitPerMinute, int limitPerHour, int limitPerDay)
      Create rate limiter 创建限流器
      Parameters:
      limitPerMinute - the limit per minute | 每分钟限制
      limitPerHour - the limit per hour | 每小时限制
      limitPerDay - the limit per day | 每天限制
  • Method Details

    • tryAcquire

      public boolean tryAcquire(String phone)
      Try to acquire permit 尝试获取许可
      Parameters:
      phone - the phone number | 手机号
      Returns:
      true if allowed | 如果允许返回true
    • acquire

      public void acquire(String phone)
      Acquire permit or throw 获取许可或抛出异常
      Parameters:
      phone - the phone number | 手机号
      Throws:
      SmsRateLimitException - if rate limited | 如果被限流
    • getRetryAfter

      public Duration getRetryAfter(String phone)
      Get retry after duration 获取重试等待时间
      Parameters:
      phone - the phone number | 手机号
      Returns:
      the duration to wait | 等待时间
    • getCurrentCount

      public int getCurrentCount(String phone)
      Get current count for phone 获取手机号当前计数
      Parameters:
      phone - the phone number | 手机号
      Returns:
      the count today | 今日计数
    • reset

      public void reset(String phone)
      Reset limits for phone 重置手机号的限制
      Parameters:
      phone - the phone number | 手机号
    • clear

      public void clear()
      Clear all records 清除所有记录
    • close

      public void close()
      Specified by:
      close in interface AutoCloseable
    • getLimitPerMinute

      public int getLimitPerMinute()
      Get limit per minute 获取每分钟限制
      Returns:
      the limit | 限制
    • getLimitPerHour

      public int getLimitPerHour()
      Get limit per hour 获取每小时限制
      Returns:
      the limit | 限制
    • getLimitPerDay

      public int getLimitPerDay()
      Get limit per day 获取每天限制
      Returns:
      the limit | 限制