Class PercentageStrategy

java.lang.Object
cloud.opencode.base.feature.strategy.PercentageStrategy
All Implemented Interfaces:
EnableStrategy

public class PercentageStrategy extends Object implements EnableStrategy
Percentage Strategy 百分比策略

Strategy that enables feature for a percentage of requests.

为一定百分比的请求启用功能的策略。

Features | 主要功能:

  • Percentage-based rollout - 基于百分比的灰度发布
  • Consistent results for same user (via hashCode) - 同一用户结果一致(通过hashCode)
  • Random for anonymous requests - 匿名请求随机

Comparison with ConsistentPercentageStrategy | 与ConsistentPercentageStrategy对比:

AspectPercentageStrategyConsistentPercentageStrategy
Hash algorithmhashCode()SHA-256
No userIdRandomReturns false
Feature-specificNoYes (includes feature key)
Salt supportNoYes

When to use | 何时使用:

  • Use this strategy for simple rollouts where anonymous users should be included
  • 使用此策略进行简单的灰度发布,允许匿名用户参与
  • Use ConsistentPercentageStrategy when you need strict user tracking or cryptographic security
  • 当需要严格的用户跟踪或加密安全时,使用ConsistentPercentageStrategy

Usage Examples | 使用示例:

// 10% rollout
Feature feature = Feature.builder("new-feature")
    .percentage(10)
    .build();

// or directly
Feature feature = Feature.builder("new-feature")
    .strategy(new PercentageStrategy(10))
    .build();

Security | 安全性:

  • Thread-safe: Yes - 线程安全: 是
  • Null-safe: Partial (validates inputs) - 空值安全: 部分(验证输入)
Since:
JDK 25, opencode-base-feature V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Constructor Details

    • PercentageStrategy

      public PercentageStrategy(int percentage)
      Create percentage strategy 创建百分比策略
      Parameters:
      percentage - the percentage (0-100) | 百分比 (0-100)
  • Method Details

    • isEnabled

      public boolean isEnabled(Feature feature, FeatureContext context)
      Check if enabled based on percentage 基于百分比检查是否启用

      If userId is present, uses consistent hashing to ensure the same user always gets the same result.

      如果存在userId,使用一致性哈希确保同一用户始终得到相同结果。

      Specified by:
      isEnabled in interface EnableStrategy
      Parameters:
      feature - the feature | 功能
      context - the context | 上下文
      Returns:
      true if enabled | 如果启用返回true
    • getPercentage

      public int getPercentage()
      Get the percentage value 获取百分比值
      Returns:
      percentage | 百分比
    • toString

      public String toString()
      Overrides:
      toString in class Object