Job queue as SQL table with multiple consumers (PostgreSQL)

后端 未结 7 851
醉梦人生
醉梦人生 2020-12-04 09:34

I have a typical producer-consumer problem:

Multiple producer applications write job requests to a job-table on a PostgreSQL database.

The job requests have

7条回答
  •  星月不相逢
    2020-12-04 10:20

    No need to do a whole table lock for this :\.

    A row lock created with for update works just fine.

    See https://gist.github.com/mackross/a49b72ad8d24f7cefc32 for the change I made to apinstein's answer and verified that it still works.

    Final code is

    update 
        tx_test_queue
    set 
        status='running'
    where
        job_id in (
            select
                job_id
            from
                tx_test_queue
            where
                status='queued'
            order by 
                job_id asc
            limit 1 for update
        )
    returning job_id;
    

提交回复
热议问题