暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

初始化PostgreSQL集簇,创建属于自己的数据库,数据库入门从这里开始

开源无限 2024-12-05
42

作者在数据库内核设计从业十余年;设计开发分布式数据内核;编写从零手写数据库教程;现在将过去的数据库内核经验一一分享,有兴趣的朋友加个关注。

一、前言

postgresql 数据库是一款通用的关系型数据,在开源数据库中能与商业数据媲美,在业界也越来越流行。

因为是开源数据库,不仅公开源码,还有很多使用案例,好用的插件,所以它的慢慢变成了数据库的先驱和标准,通过postgresql可以很好从使用到原理,彻底搞懂;

如果是学习编程,也可以学到丰富的编程知识,数据结构,编程技巧,它里面还有很多精妙的架构设计,分层思想,可以灵活定制的思想。

本专栏主要介绍postgresql 入门使用,数据库维护管理,通过这些使用来了解数据库原理,慢慢了解postgresql是什么样的数据库,能做那些事情,以及如何做好服务,最关键的是这些知识都是面试的必备项。

二、概述

本文主要介绍postgresql 的数据库集群,它的初始化,配置,以及它的物理结构。

在源码编译安装后,第一步就是初始化集群, 而通过安装包安装后,已经初始化了一个默认的数据库集群,启动服务后就可以直接进行SQL命令操作。

而在我们应用部署时,不同的应用往往使用不同的数据库集群目录,在物理上进行隔离,那么我们就需要对不同应用分别初始化各自的数据库集群。


三、原理

我们知道数据库主要是帮助存储和管理数据,方便我们检索,那么数据库存储数据的目录,这在postgresql中叫做集群目录,有些翻译的叫集簇目录。

集群目录下面,存放用户的数据,如创建的表,用户,索引等数据外,还有数据库组织数据,如数据库与表的映射关系,数据库的数量,表的结构定义等,我们称之为数据字典; 另外,还有一类数据是为了数据库服务运行稳定,高性能的辅助数据,如系统字典的缓存数据,空闲空间的管理数据等等。

数据库服务运行时,就会从这个目录下进行加载,所以这个目录非常重要,在实际项目中,都会有专门的系统用户才可以操作,同时还要对它进行冷备,还要进行各种策略的热备。

呃,泄漏了删库跑路原来这样子的,什么都没说。。。

四、命令介绍

在安装目录下的bin目录中,有初始化数据库集群的命令 initdb,我们一起来看下它的介绍。

    [senllang@hatch postgres]$ ll
    total 16
    drwxr-xr-x. 2 senllang develops 4096 Aug 2 09:26 bin
    drwxr-xr-x. 6 senllang develops 4096 Aug 2 09:24 include
    drwxr-xr-x. 4 senllang develops 4096 Aug 2 09:26 lib
    drwxr-xr-x. 7 senllang develops 4096 Aug 2 09:26 share
    [senllang@hatch postgres]$ cd bin/

    安装后的目录大概有以下四个子目录,bin 命令目录 include 是开发所需的头文件,lib是开发所需的库,share中包括模版配置文件,插件等

    查看帮助

      [senllang@hatch bin]$ ./initdb --help
      initdb initializes a PostgreSQL database cluster.


      Usage:
      initdb [OPTION]... [DATADIR]


      Options:
      -A, --auth=METHOD default authentication method for local connections
      --auth-host=METHOD default authentication method for local TCP/IP connections
      --auth-local=METHOD default authentication method for local-socket connections
      [-D, --pgdata=]DATADIR location for this database cluster
      -E, --encoding=ENCODING set default encoding for new databases
      -g, --allow-group-access allow group read/execute on data directory
      --icu-locale=LOCALE set ICU locale ID for new databases
      --icu-rules=RULES set additional ICU collation rules for new databases
      -k, --data-checksums use data page checksums
      --locale=LOCALE set default locale for new databases
      --lc-collate=, --lc-ctype=, --lc-messages=LOCALE
      --lc-monetary=, --lc-numeric=, --lc-time=LOCALE
      set default locale in the respective category for
      new databases (default taken from environment)
      --no-locale equivalent to --locale=C
      --locale-provider={libc|icu}
      set default locale provider for new databases
      --pwfile=FILE read password for the new superuser from file
      -T, --text-search-config=CFG
      default text search configuration
      -U, --username=NAME database superuser name
      -W, --pwprompt prompt for a password for the new superuser
      -X, --waldir=WALDIR location for the write-ahead log directory
      --wal-segsize=SIZE size of WAL segments, in megabytes


      Less commonly used options:
      -c, --set NAME=VALUE override default setting for server parameter
      -d, --debug generate lots of debugging output
      --discard-caches set debug_discard_caches=1
      -L DIRECTORY where to find the input files
      -n, --no-clean do not clean up after errors
      -N, --no-sync do not wait for changes to be written safely to disk
      --no-instructions do not print instructions for next steps
      -s, --show show internal settings
      -S, --sync-only only sync database files to disk, then exit


      Other options:
      -V, --version output version information, then exit
      -?, --help show this help, then exit


      If the data directory is not specified, the environment variable PGDATA
      is used.


      Report bugs to <pgsql-bugs@lists.postgresql.org>.
      PostgreSQL home page: <https://www.postgresql.org/>


      参数说明

      常用的参数,主要有

      -D 指定集群目录所在的路径,这是必选的参数;比如~/testdemo,那么testdemo就是集群目录, 当然也可以设置环境变量 PGDATA 来代替-D-U 指定数据库的超级管理员用户名,它具有所有权限,这是可选参数;如果不指定,默认数据库超级管理员与当前的系统用户名 同名;-W 提示输入密码,这个密码是超级管理员用户的登陆密码;这也是可选参数,默认为空;

      其它参数,可以在后继学习中再了解。

      五、初始化集群

      了解了初始化集群命令后,现在让我们初始化一个属于我们自己的数据库集群。

      在当前目录下,创建testdemo的数据库集群目录,同时将数据库超级用户命名为postgres

        [senllang@hatch bin]$ ./initdb -D testdemo -W -U postgres
        The files belonging to this database system will be owned by user "senllang".
        This user must also own the server process.


        Using default ICU locale "en_US".
        Using language tag "en-US" for ICU locale "en_US".
        The database cluster will be initialized with this locale configuration:
        provider: icu
        ICU locale: en-US
        LC_COLLATE: en_US.UTF-8
        LC_CTYPE: en_US.UTF-8
        LC_MESSAGES: en_US.UTF-8
        LC_MONETARY: en_US.UTF-8
        LC_NUMERIC: en_US.UTF-8
        LC_TIME: en_US.UTF-8
        The default database encoding has accordingly been set to "UTF8".
        The default text search configuration will be set to "english".


        Data page checksums are disabled.


        Enter new superuser password:
        Enter it again:


        creating directory testdemo ... ok
        creating subdirectories ... ok
        selecting dynamic shared memory implementation ... posix
        selecting default max_connections ... 100
        selecting default shared_buffers ... 128MB
        selecting default time zone ... Asia/Shanghai
        creating configuration files ... ok
        running bootstrap script ... ok
        performing post-bootstrap initialization ... ok
        syncing data to disk ... ok


        initdb: warning: enabling "trust" authentication for local connections
        initdb: hint: You can change this by editing pg_hba.conf or using the option -A, or --auth-local and --auth-host, the next time you run initdb.


        Success. You can now start the database server using:


        pg_ctl -D testdemo -l logfile start

        这样在当前目录下,就生成了一个testdemo的目录,里面有好多子目录和文件,下面我们来认识一下。

        六、集群目录

          [senllang@hatch bin]$ cd testdemo/
          [senllang@hatch testdemo]$ ll
          total 56
          drwx------. 5 senllang develops 33 Sep 2 14:42 base
          drwx------. 2 senllang develops 4096 Sep 2 14:42 global
          drwx------. 2 senllang develops 6 Sep 2 14:42 pg_commit_ts
          drwx------. 2 senllang develops 6 Sep 2 14:42 pg_dynshmem
          -rw-------. 1 senllang develops 5711 Sep 2 14:42 pg_hba.conf
          -rw-------. 1 senllang develops 2640 Sep 2 14:42 pg_ident.conf
          drwx------. 4 senllang develops 68 Sep 2 14:42 pg_logical
          drwx------. 4 senllang develops 36 Sep 2 14:42 pg_multixact
          drwx------. 2 senllang develops 6 Sep 2 14:42 pg_notify
          drwx------. 2 senllang develops 6 Sep 2 14:42 pg_replslot
          drwx------. 2 senllang develops 6 Sep 2 14:42 pg_serial
          drwx------. 2 senllang develops 6 Sep 2 14:42 pg_snapshots
          drwx------. 2 senllang develops 25 Sep 2 14:42 pg_stat
          drwx------. 2 senllang develops 6 Sep 2 14:42 pg_stat_tmp
          drwx------. 2 senllang develops 18 Sep 2 14:42 pg_subtrans
          drwx------. 2 senllang develops 6 Sep 2 14:42 pg_tblspc
          drwx------. 2 senllang develops 6 Sep 2 14:42 pg_twophase
          -rw-------. 1 senllang develops 3 Sep 2 14:42 PG_VERSION
          drwx------. 3 senllang develops 60 Sep 2 14:42 pg_wal
          drwx------. 2 senllang develops 18 Sep 2 14:42 pg_xact
          -rw-------. 1 senllang develops 88 Sep 2 14:42 postgresql.auto.conf
          -rw-------. 1 senllang develops 29708 Sep 2 14:42 postgresql.conf

          先来看几个重要的目录和文件

          base 目录 它里面存储各个database中的数据,包括table,index, sequence, view等等;pg_wal 目录 存放我们常说的redo日志log 目录 数据库服务运行的日志,上图中没有,默认没有打开日志输出到文件的开关postgresql.conf 数据库服务的配置文件,比如数据库服务的监听IP,端口等大量配置pg_hba.conf 主机访问控制的配置文件,默认只能本机登陆,如果需要远程访问,就需要配置许可;

          其它文件我们后面慢慢了解;

          七、配置文件

          我们重点介绍 数据库配置文件和主机访问控制配置,先来介绍几个入门级参数,这样就可以解决刚开始使用的问题,其它参数会随着其它功能介绍一起了解。

          数据库配置

          默认参数的前面都会加 # ,如果需要修改的话,需要去掉前面的#,修改才能生效。

          监听配置

          默认localhost 和 5432,如果要远程客户端访问,可以修改为具体IP或*

            listen_addresses = '*'
            # port = 5432

            数据库连接数

            数据库服务启动时,内存分配,锁的分配都和连接数有关,当然也不能无限大,默认连接数为100,这里可以根据自己的需求修改, 越大占用的内存和系统资源越多,够用即可;

              max_connections = 100

              数据库缓存大小

              在select查询或insert插入数据时,并不是直接操作磁盘上的文件,而是操作缓存中的数据,如果数据不在缓存中,才会与磁盘进行交互,所以缓存当然是越大越好,能把需要的数据都加载进来,那性能就会提升。

              默认是128MB,当然根据自己的数据量和机器的内存来定,如果只是尝试一下,默认也足够了,如果发现磁盘的IO很高,那就需要适当调大一些;

                shared_buffers = 128MB 

                数据库运行日志

                调试过程序的都知道,运行日志的重要性,默认是关闭的,也就是不输出到文件中,建议打开,这样在发生异常时,可以通过运行日志文件来分析;

                  logging_collector = on 

                  主机访问控制

                  数据库有严格的访问控制,可以精确到某个database, user, 或网段,它的配置格式如下

                    # local         DATABASE  USER  METHOD  [OPTIONS]
                    # host DATABASE USER ADDRESS METHOD [OPTIONS]
                    # hostssl DATABASE USER ADDRESS METHOD [OPTIONS]
                    # hostnossl DATABASE USER ADDRESS METHOD [OPTIONS]
                    # hostgssenc DATABASE USER ADDRESS METHOD [OPTIONS]
                    # hostnogssenc DATABASE USER ADDRESS METHOD [OPTIONS]

                    我们想到配置远程访问,比如图形化客户端访问,可以加入一行, 允许所有IP可以访问所有数据库,必须使用密码校验。

                      host    all             all             0.0.0.0/0            md5

                      八、总结

                      通过本文,分享了postgresql 数据存储目录-数据集群目录概念,初始化数据库集群,以及一些入门级参数配置,期待您的反馈和加入。

                      文章转载自开源无限,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

                      评论