天天看點

PostgreSQL 按需切片的實作(TimescaleDB插件自動切片功能的plpgsql schemaless實作)

PostgreSQL , schemaless , 自動切片 , track_count , 計數器 , udf , plpgsql , timescaledb

TimescaleDB是PostgreSQL的一款時序資料庫插件,其中自動切片是一個非常深入人心的功能。

<a href="http://www.timescale.com/">http://www.timescale.com/</a>

<a href="https://github.com/digoal/blog/blob/master/201711/20171102_02_pic_001.jpg" target="_blank"></a>

實際上PostgreSQL plpgsql也可以實作類似的功能,當然,前提是需要使用schemaless的模式。

schemaless的設計思路和應用舉例:

<a href="https://github.com/digoal/blog/blob/master/201711/201709/20170927_03.md">《PostgreSQL 在鐵老大訂單系統中的schemaless設計和性能壓測》</a>

<a href="https://github.com/digoal/blog/blob/master/201711/201705/20170511_01.md">《PostgreSQL schemaless 的實作(類mongodb collection)》</a>

<a href="https://github.com/digoal/blog/blob/master/201711/201704/20170417_01.md">《PostgreSQL 時序最佳實踐 - 證券交易系統資料庫設計 - 阿裡雲RDS PostgreSQL最佳實踐》</a>

下面,就自動切片這個功能,我們看看schemaless的實作例子。

1、首先要監測寫入量,通過track_counts參數,可以給資料的寫入計數(預設track_counts參數是開啟的)。

<a href="https://github.com/digoal/blog/blob/master/201711/20171101_01.md">《PostgreSQL pg_stat_reset清除track_counts的隐患》</a>

2、當資料寫入到一定量時,自動寫下一張表。

1、設計:

寫入時,通過UDF寫入,并且實時監控每種資料流的寫入速度,并動态做資料分片。

2、測試表:

3、分片規則:

當記錄數超過100000時,自動切換分區。

4、UDF定義:

5、壓測

自動切片成功:

timescaleDB插件還有很多其他的功能,在使用友善也更加的邊界,待TimescaleDB插件成熟,還是推薦使用TimescaleDB。

對于阿裡雲RDS PG,使用本文提到的方法,還可以實作實時寫入RDS PG,同時根據設定的門檻值,批量寫入OSS外部表(寫OSS外部表可以使用DBLINK的異步接口)。

<a href="https://github.com/digoal/blog/blob/master/201709/20170906_01.md">《阿裡雲RDS PostgreSQL OSS 外部表 - (dblink異步調用封裝)并行寫提速案例》</a>

<a href="https://github.com/digoal/blog/blob/master/201711/20171102_02_pic_002.jpg" target="_blank"></a>

繼續閱讀