Laravel tạo service BloomFilterService có chức năng kiểm tra nhanh email , có thể áp dụng vào nhiều việc khác

Laravel tạo service BloomFilterService có chức năng kiểm tra nhanh email , có thể áp dụng vào nhiều việc khác

Dưới đây là đoạn code :

<?php

namespace App\Services;

use Illuminate\Support\Facades\Redis;

class BloomFilterService
{
    protected int $size;
    protected int $hashFunctions;
    protected string $redisKey;
    protected \Illuminate\Redis\Connections\Connection $redisconnect;
    /*
        size 1,000,000 số email lưu trũ : ~100,000 email tốn ~0.12MB
        size 10,000,000 số email lưu trũ : ~1.000,000 email tốn ~1.25MB
        size 100,000,000 số email lưu trũ : ~10.000,000 email tốn ~12.5MB
     */
    public function __construct(int $size = 10000000, string $connect_key = 'default', $hashFunctions = 10 , string $redisKey = 'bloom_filter_emails')
    {
        $this->size = $size; // Tăng kích thước filter
        $this->redisKey = $redisKey;
        $this->redisconnect = Redis::connection($connect_key);
        $this->hashFunctions = $hashFunctions;
    }

    private function hash($value, $seed)
    {
        return abs(crc32($value . $seed) % $this->size);
    }

    // ✅ Dùng BITSET thay vì Redis Set để tiết kiệm bộ nhớ
    public function add($email)
    {
        for ($i = 0; $i < $this->hashFunctions; $i++) {
            $index = $this->hash($email, $i);
            $this->redisconnect->setbit($this->redisKey, $index, 1);
        }
    }

    // ✅ Kiểm tra hiệu quả hơn với GETBIT
    public function mightContain($email)
    {
        for ($i = 0; $i < $this->hashFunctions; $i++) {
            $index = $this->hash($email, $i);
            if (!$this->redisconnect->getbit($this->redisKey, $index)) {
                return false;
            }
        }
        return true;
    }

    // ✅ Xóa toàn bộ Bloom Filter
    public function clear()
    {
        $this->redisconnect->del($this->redisKey);
    }
}