sequence cache
从上面可以看到,sequence 默认的 cache 是1。
在高并发的系统中,为了提高性能,可以增大 cache,如 10,即一次将 sequence 的10个数值 load 到内存中。这样,只需要访问 sequence 1 次,而不是10次。
下面,将 sequence tb_test_bigserial_test_id_seq
的 cache 改成 10:
alvindb=> SELECT pg_backend_pid();
pg_backend_pid
----------------
16649
(1 row)
alvindb=> ALTER SEQUENCE tb_test_bigserial_test_id_seq CACHE 10;
ALTER SEQUENCE
alvindb=> \d tb_test_bigserial_test_id_seq
Sequence "alvin.tb_test_bigserial_test_id_seq"
Type | Start | Minimum | Maximum | Increment | Cycles? | Cache
--------+-------+---------+---------------------+-----------+---------+-------
bigint | 1 | 1 | 9223372036854775807 | 1 | no | 10
Owned by: alvin.tb_test_bigserial.test_id
在 session 1(pid 16649)中插入数据
alvindb=> INSERT INTO tb_test_bigserial(create_time) VALUES (DEFAULT);
INSERT 0 1
alvindb=> INSERT INTO tb_test_bigserial(create_time) VALUES (DEFAULT);
INSERT 0 1
alvindb=> SELECT * FROM tb_test_bigserial ORDER BY 2 DESC;
test_id | create_time
---------+----------------------------
2 | 2021-05-01 15:21:00.116979
1 | 2021-05-01 15:20:56.405149
(2 rows)
alvindb=> SELECT * FROM tb_test_bigserial_test_id_seq;
last_value | log_cnt | is_called
------------+---------+-----------
10 | 32 | t
(1 row)
alvindb=> SELECT lastval();
lastval
---------
2
(1 row)
从以上结果可以看到,此 session 中一次取了10个数据,last_value
是10,is_called
是 true,即新的 session 中从11开始。
lastval() 是2,即当前 session 中,上一次 nextval 返回的是2。需要注意,lastval() 并没有参数,即它返回最近任意 sequence 的 nextval 值。
如下,
alvindb=> SELECT nextval('tb_test_sequence_rename_test_id_seq2');
nextval
---------
1
(1 row)
alvindb=> SELECT lastval();
lastval
---------
1
(1 row)
在 session 2(pid 14287)中插入数据:
alvindb=> SELECT pg_backend_pid();
pg_backend_pid
----------------
14287
(1 row)
alvindb=> INSERT INTO tb_test_bigserial(create_time) VALUES (DEFAULT);
INSERT 0 1
alvindb=> INSERT INTO tb_test_bigserial(create_time) VALUES (DEFAULT);
INSERT 0 1
alvindb=> SELECT * FROM tb_test_bigserial ORDER BY 2 DESC;
test_id | create_time
---------+----------------------------
12 | 2021-05-01 15:22:02.582036
11 | 2021-05-01 15:22:01.313919
2 | 2021-05-01 15:21:00.116979
1 | 2021-05-01 15:20:56.405149
(4 rows)
alvindb=> SELECT * FROM tb_test_bigserial_test_id_seq;
last_value | log_cnt | is_called
------------+---------+-----------
20 | 32 | t
(1 row)
alvindb=> SELECT lastval();
lastval
---------
12
(1 row)
从以上结果可以看到,虽然在 session 1中,sequence tb_test_bigserial_test_id_seq
只取了两次值,但 session 2中是从11开始取值的。
因为 cache 是10,所以1-10是预留给了 session 1。11-20是预留给了 sessio