PHP简易灰度方案

<?php

// PHP简易灰度方案
class test
{
    // userId % 100 < x #使用userId取模获取,比如放量下x%

    /**
     * 对100取余
     * @param string $userId
     * @return int
     */
    public function getRemainder(string $userId)
    {
//        return $userId % 100;
        //这个key,每个业务自己随便生成一个唯一的即可,可以网上找个工具
        //https://suijimimashengcheng.bmcx.com/
        $key = "Z1SbMB";
//        $key = "999488";
        //  对userId进行加盐(key),然后md5加密(
        $md5Str = md5($key . $userId);
        //这个地方取前6位进行转换,因为取全部,算出来太长,最主要的是在长度超长的情况下
        $substring = substr($md5Str, 0, 6);
        //将16进制转换为10进制
        return hexdec($substring) % 100;
    }
}

// mysql
// conv(substr(md5(concat('Z1SbMB',0)),1,6),16,10)%100
// select id,conv(substr(md5(concat('Z1SbMB',id)),1,6),16,10)%100 as number from admin where id = 3;

$hit = 50; // 命中率
$test = new test();
//$userId = strval(3);
$userId = strval(rand(0, 100000));
$remainder = $test->getRemainder($userId);
echo $userId . ':' . $remainder . ",";
if ($remainder < $hit) {
    echo "命中" . "\n";
} else {
    echo "丢失" . "\n";
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值