백엔드 개발 PHP 튜토리얼 Laravel 지연 대기열 구현의 Lua 스크립트 분석

Laravel 지연 대기열 구현의 Lua 스크립트 분석

Apr 16, 2018 pm 02:29 PM
laravel 성취하다 각본

이 글은 주로 Laravel 지연 대기열 구현에 대한 Lua 스크립트 분석을 소개합니다. 이제 이를 공유합니다. 도움이 필요한 친구들이 참고할 수 있습니다.

Laravel은 Redis 지연 대기열을 구현할 때 Lua 스크립트를 사용합니다. 서로 다른 대기열 간의 작업 원자성을 보장합니다
Laravel5.1에서는 서로 다른 대기열의 작업의 원자성을 보장하기 위해 주로 네 가지 Lua 스크립트 메서드가 사용됩니다.

1 대기열 작업 수를 계산하는 방법

1.llen 개수 계산 of list queues

2. zcard는 zset 대기열 데이터 볼륨을 계산합니다

    /**
     * Get the Lua script for computing the size of queue.
     *
     * KEYS[1] - The name of the primary queue
     * KEYS[2] - The name of the "delayed" queue
     * KEYS[3] - The name of the "reserved" queue
     *
     * @return string
     */
    public static function size()
    {
        return <<<'LUA'
             return redis.call('llen', KEYS[1]) + redis.call('zcard', KEYS[2]) + 
             redis.call('zcard', KEYS[3])
        LUA;
    }
로그인 후 복사

2. 팝 대기열 작업을 예약 대기열에 넣습니다

    /**
     * Get the Lua script for popping the next job off of the queue.
     *
     * KEYS[1] - The queue to pop jobs from, for example: queues:foo
     * KEYS[2] - The queue to place reserved jobs on, for example: queues:foo:reserved
     * ARGV[1] - The time at which the reserved job will expire
     *
     * @return string
     */
    public static function pop()
    {
      return <<<'LUA'
          -- Pop the first job off of the queue...
         local job = redis.call('lpop', KEYS[1])
         local reserved = false

         if(job ~= false) then
            -- Increment the attempt count and place job on the reserved queue...
            reserved = cjson.decode(job)
            reserved['attempts'] = reserved['attempts'] + 1
            reserved = cjson.encode(reserved)
            redis.call('zadd', KEYS[2], ARGV[1], reserved)
         end
        return {job, reserved}
      LUA;
    }
로그인 후 복사

3. 예약 대기열의 작업을 지연 대기열에 추가합니다

    /**
     * Get the Lua script for releasing reserved jobs.
     *
     * KEYS[1] - The "delayed" queue we release jobs onto, for example: queues:foo:delayed
     * KEYS[2] - The queue the jobs are currently on, for example: queues:foo:reserved
     * ARGV[1] - The raw payload of the job to add to the "delayed" queue
     * ARGV[2] - The UNIX timestamp at which the job should become available
     *
     * @return string
     */
    public static function release()
    {
        return <<<'LUA'
           -- Remove the job from the current queue...
           redis.call('zrem', KEYS[2], ARGV[1])
           -- Add the job onto the "delayed" queue...
           redis.call('zadd', KEYS[1], ARGV[2], ARGV[1])
           return true
        LUA;
    }
로그인 후 복사

4. 시간에 맞는 예약된 대기열의 작업 실행 대기열에 병합됨

    /**
     * Get the Lua script to migrate expired jobs back onto the queue.
     *
     * KEYS[1] - The queue we are removing jobs from, for example: queues:foo:reserved
     * KEYS[2] - The queue we are moving jobs to, for example: queues:foo
     * ARGV[1] - The current UNIX timestamp
     *
     * @return string
     */
    public static function migrateExpiredJobs()
    {
        return <<<'LUA'
        -- Get all of the jobs with an expired "score"...
           local val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1])

        -- If we have values in the array, we will remove them from the first queue
        -- and add them onto the destination queue in chunks of 100, which moves
        -- all of the appropriate jobs onto the destination queue very safely.
           if(next(val) ~= nil) then
             redis.call('zremrangebyrank', KEYS[1], 0, #val - 1)

             for i = 1, #val, 100 do
               redis.call('rpush', KEYS[2], unpack(val, i, math.min(i+99, #val)))
             end
           end
          return val
        LUA;
}
로그인 후 복사

                                                                                                                                       ’

위 내용은 Laravel 지연 대기열 구현의 Lua 스크립트 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

뜨거운 기사 태그

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PHP 대 Flutter: 모바일 개발을 위한 최고의 선택 PHP 대 Flutter: 모바일 개발을 위한 최고의 선택 May 06, 2024 pm 10:45 PM

PHP 대 Flutter: 모바일 개발을 위한 최고의 선택

Laravel - 장인 명령 Laravel - 장인 명령 Aug 27, 2024 am 10:51 AM

Laravel - 장인 명령

PHP 단위 테스트 도구의 장점과 단점 분석 PHP 단위 테스트 도구의 장점과 단점 분석 May 06, 2024 pm 10:51 PM

PHP 단위 테스트 도구의 장점과 단점 분석

PHP에서 ORM(객체 관계형 매핑)을 사용하여 데이터베이스 작업을 단순화하는 방법은 무엇입니까? PHP에서 ORM(객체 관계형 매핑)을 사용하여 데이터베이스 작업을 단순화하는 방법은 무엇입니까? May 07, 2024 am 08:39 AM

PHP에서 ORM(객체 관계형 매핑)을 사용하여 데이터베이스 작업을 단순화하는 방법은 무엇입니까?

PHP 분산 시스템 아키텍처 및 실습 PHP 분산 시스템 아키텍처 및 실습 May 04, 2024 am 10:33 AM

PHP 분산 시스템 아키텍처 및 실습

Laravel과 CodeIgniter의 최신 버전 비교 Laravel과 CodeIgniter의 최신 버전 비교 Jun 05, 2024 pm 05:29 PM

Laravel과 CodeIgniter의 최신 버전 비교

Laravel과 CodeIgniter의 데이터 처리 기능은 어떻게 비교됩니까? Laravel과 CodeIgniter의 데이터 처리 기능은 어떻게 비교됩니까? Jun 01, 2024 pm 01:34 PM

Laravel과 CodeIgniter의 데이터 처리 기능은 어떻게 비교됩니까?

PHP 코드 단위 테스트 및 통합 테스트 PHP 코드 단위 테스트 및 통합 테스트 May 07, 2024 am 08:00 AM

PHP 코드 단위 테스트 및 통합 테스트

See all articles