Aldebaran

人生最棒的感觉,就是你做到别人说你做不到的事。

0%

Clickhouse分布式集群搭建

生田絵梨花 - 白石麻衣

ClickHouse概述

  • 什么是ClickHouse?

    ClickHouse 是俄罗斯的Yandex于2016年开源的列式存储数据库(DBMS),主要用于在线分析处理查询(OLAP),能够使用SQL查询实时生成分析数据报告。

  • 什么是列式存储

    以下面表为例

    id website wechat
    1 https://www.baidu.com/ 百度
    2 https://www.google.com/ 谷歌

    采用行式存储时,数据在磁盘上的组织结构为:

    Row1 Row2
    1 https://www.baidu.com/ 百度 2 https://www.google.com/

    好处是想查某条记录所有的属性时,可以通过一次磁盘查找加顺序读取就可以。但是当想查所有记录wechat时,需要不停的查找,或者全表扫描才行,遍历的很多数据都是不需要的。

    而采用列式存储时,数据在磁盘上的组织结构为:

    col1 col2 col3
    1 2 https://www.baidu.com/ https://www.google.com/ 百度 谷歌

    这时想查所有记录的wechat只需把col3那一列拿出来即可。

  • ClickHouse核心的配置文件

    • (1):/etc/clickhouse-server/config.xml 端口配置、本地机器名配置、内存设置等;config.xml 核心配置文件中文解释:
    • (2):/etc/clickhouse-server/metrika.xml 集群配置、ZK配置、分片配置等;metrika.xml核心配置文件中文注解:
    • (3):/etc/clickhouse-server/users.xml 权限、配额设置;user.xml核心配置文件中文注解:
  • ClickHouse表引擎

    CK里面有非常多的引擎,这里只推荐3个:

      MergeTree,是CK里最Advanced的引擎,性能超高,单机写入可以达到50w峰值,查询性能非常快,有兴趣看我其他文章
    
      ReplicatedMergeTree,基于MergeTree,同时引入ZK,做了复制,下文会说
    
      Distributed,分布式引擎,本身不存储数据,可认为就是一张View,如果写入,会把请求丢到集群里的节点(有算法控制),如果查询,会帮你做查询转发再聚合返回
    
  • ClickHouse数据复制

    • 基于ReplicatedMergeTree+Zookeeper的表复制

      1:使用的是复制表ReplicatedMergeTree+Zookeeper的协调一致性完成数据的复制和数据一致性

      2:数据相互复制且会进行数据验证,自动保证数据一致性

      3:建议3个节点做复制,设置至少保证2个节点收到数据才算成功,增强数据的一致性

      4:关于复制引擎,ClickHouse官方建议不搞特别大的集群,建议一个业务就跑一个集群,具体多少分片,自己衡量

    • 基于cluster+Distributed的复制

      1:使用分布式表Distributed,集群的分片的副本的自动复制

      2:参数internal_replication要设置false 写全部的分片,不建议:poor man replication

      3:仅仅对分布式表写入:并且在internal_replication=false的情况下,会写入分布式表对应的子表

      4:推荐使用的方式:

      (1):写分布式表的情况下,设置true,即只写一个shard里面的一个副本

      (2):开启表级别的复制,无论哪一个副本被写入,副本数据都会被同步到其他副本节点

  • 性能建议

    通常情况在一个在合理硬件配置下单机运行的ClickHouse在面对相当数据量的计算时都能够达到相当不错的性能,当性能不能满足要求时,增强单机的配置(CPU升级、内存增加)或是进行横向扩展做集群都能够有较好的改善。

    在数据量较大情况下对内存的需求会很高(如设置了排序),在内存充足时所有计算都是基于内存的,如果不够充足,在一些情况下会导致ClickHouse该类计算时性能有所下降(由于会进行基于磁盘的计算),某些查询在数据量过大时会直接导致计算无法完成,甚至ClickHouse服务崩溃重启,对于这类情况建议增大ClickHouse机器内存并修改内存相关配置,添加机器使用多机集群也会有一定改善。

    其他ClickHouse官网提供的性能建议:

    • ClickHouse能够最大程度利用系统资源,CPU核心数的增加相比CPU主频的提升对性能的改善更大。(即CPU核心数>CPU主频)
    • 不要禁用CPU的超线程,它对一些查询有帮助。
    • 建议CPU超频,对性能提升有帮助。
    • 内存的提高能够让ClickHouse更多地使用缓存提高查询效率;对于数据压缩后超过200GB的大数据,建议提供足够大的内存(如128GB RAM)以缓存热数据。即使对于超过2TB的存储数据,128GB内存较64GB内存性能提升也很明显。
    • 除非部署于个人笔记本上,否则建议禁用系统交换文件(swap file)。
    • 禁用内核的透明大页内存(transparent huge pages),该选项会导致明显的性能下降。命令: echo ‘never’ | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
    • 如果资金允许,可以使用SSD硬盘,否则7200rpm SATA硬盘也可以。
    • 如果不使用SSD硬盘,可以使用RAID-10, RAID-5, RAID-6 或 RAID-50磁盘阵列。对于Linux系统推荐使用软件 RAID(mdadm),且不建议使用LVM。如果资金允许,建议使用RAID-10。如果拥有超过4块磁盘,建议使用RAID-6或RAID-50而不是RAID-5。当使用RAID-5, RAID-6 或 RAID-50时,建议增加stripe_cache_size。RAID块大小1025KB足够,不要过大或过小。启用长队列NCQ,对于HDD选择CFQ调度器,对于SSD使用noop。不要减少’readahead’设置,对于HDD启用写缓存。
    • 文件系统建议使用 ext4, 并使用选项 noatime, nobarrier。
    • 如果可以,至少使用10GB网络,1GB也应该可以。(主要是考虑集群情况)

ClickHouse分布式集群方案

准备

  • 下面讲演示基于ReplicatedMergeTree+Zookeeper的集群方案

  • 服务器规划

    IP hostname01 hostname02
    192.168.100.161 zk01 ck01
    192.168.100.162 zk02 ck02
    192.168.100.163 zk03 ck03
  • 编辑每一台服务器上的 /etc/hosts

      $ vim /etc/hosts
      192.168.100.161 zk01
      192.168.100.162 zk02
      192.168.100.163 zk03
    
      192.168.100.161 ck01
      192.168.100.162 ck02
      192.168.100.163 ck03
    

zookeeper-3.6.2集群

zookeeper-3.6.2单机环境搭建

  1. 下载并解压

     $ cd /usr/local/src
     $ wget https://downloads.apache.org/zookeeper/zookeeper-3.6.2/apache-zookeeper-3.6.2-bin.tar.gz
     $ tar xf apache-zookeeper-3.6.2-bin.tar.gz && mv apache-zookeeper-3.6.2-bin /usr/local/apache-zookeeper-3.6.2-bin
     $ ln -s /usr/local/apache-zookeeper-3.6.2-bin /usr/local/zookeeper
    
  2. 修改环境变量

    编辑 /etc/profile 文件, 在文件末尾添加以下环境变量配置:

     # ZooKeeper Env
     export ZOOKEEPER_HOME=/usr/local/zookeeper
     export PATH=$PATH:$ZOOKEEPER_HOME/bin
    

    运行以下命令使环境变量生效: source /etc/profile

  3. 初始化配置文件

    初次使用 ZooKeeper 时,需要将/usr/local/zookeeper/conf 目录下的 zoo_sample.cfg 重命名为 zoo.cfg

     $ cp -rpv /usr/local/zookeeper/conf/zoo_sample.cfg /usr/local/zookeeper/conf/zoo.cfg
    

    创建目录

     $ mkdir -pv /data/zookeeper/{zookeeper_data,zookeeper_datalogs,zookeeper_logs}
    

    启动

     $ systemctl start zookeeper
    
  4. 在其他2台上面执行一样的操作。

zookeeper-3.6.2集群环境搭建

  1. 编辑配置文件

    Zookeeper 2181

    • zoo_2181.cfg

        tickTime=2000
        initLimit=10
        syncLimit=5
      
        maxClientCnxns=2000
        maxSessionTimeout=60000000
      
        4lw.commands.whitelist=*
        dataDir=/data/zookeeper/zookeeper_data/2181
        dataLogDir=/data/zookeeper/zookeeper_datalogs/2181
      
        autopurge.purgeInterval=24
        autopurge.snapRetainCount=10
      
        reconfigEnabled=true
        standaloneEnabled=false
        dynamicConfigFile=/usr/local/apache-zookeeper-3.6.2-bin/conf/zoo_replicated.2181.cfg.dynamic
      
    • zoo_replicated.2181.cfg.dynamic

        server.2181=zk01:2888:3888:participant;0.0.0.0:2181
        server.2182=zk02:2889:3889:participant;0.0.0.0:2182
        server.2183=zk03:2890:3890:participant;0.0.0.0:2183
      
    • 初始化myid

        $ echo "2181">/data/zookeeper/zookeeper_data/2181/myid
      

    Zookeeper 2182

    • zoo_2182.cfg

        tickTime=2000
        initLimit=10
        syncLimit=5
      
        maxClientCnxns=2000
        maxSessionTimeout=60000000
      
        4lw.commands.whitelist=*
        dataDir=/data/zookeeper/zookeeper_data/2182
        dataLogDir=/data/zookeeper/zookeeper_datalogs/2182
      
        autopurge.purgeInterval=24
        autopurge.snapRetainCount=10
      
        reconfigEnabled=true
        standaloneEnabled=false
        dynamicConfigFile=/usr/local/apache-zookeeper-3.6.2-bin/conf/zoo_replicated.2182.cfg.dynamic
      
    • zoo_replicated.2182.cfg.dynamic

        server.2181=zk01:2888:3888:participant;0.0.0.0:2181
        server.2182=zk02:2889:3889:participant;0.0.0.0:2182
        server.2183=zk03:2890:3890:participant;0.0.0.0:2183
      
    • 初始化myid

        $ echo "2182">/data/zookeeper/zookeeper_data/2182/myid
      

    Zookeeper 2183

    • zoo_2183.cfg

        tickTime=2000
        initLimit=10
        syncLimit=5
      
        maxClientCnxns=2000
        maxSessionTimeout=60000000
      
        4lw.commands.whitelist=*
        dataDir=/data/zookeeper/zookeeper_data/2183
        dataLogDir=/data/zookeeper/zookeeper_datalogs/2183
      
        autopurge.purgeInterval=24
        autopurge.snapRetainCount=10
      
        reconfigEnabled=true
        standaloneEnabled=false
        dynamicConfigFile=/usr/local/apache-zookeeper-3.6.2-bin/conf/zoo_replicated.2183.cfg.dynamic
      
    • zoo_replicated.2183.cfg.dynamic

        server.2181=zk01:2888:3888:participant;0.0.0.0:2181
        server.2182=zk02:2889:3889:participant;0.0.0.0:2182
        server.2183=zk03:2890:3890:participant;0.0.0.0:2183
      
    • 初始化myid

        $ echo "2183">/data/zookeeper/zookeeper_data/2183/myid
      

ClickHouse集群

ClickHouse单机环境搭建

  1. 系统要求

    ClickHouse可以在任何具有x86_64,AArch64或PowerPC64LE CPU架构的Linux,FreeBSD或Mac OS X上运行。

    官方预构建的二进制文件通常针对x86_64进行编译,并利用SSE 4.2指令集,因此,除非另有说明,支持它的CPU使用将成为额外的系统需求。下面是检查当前CPU是否支持SSE 4.2的命令:

     $ grep -q sse4_2 /proc/cpuinfo && echo "SSE 4.2 supported" || echo "SSE 4.2 not supported"
    

    要在不支持SSE 4.2或AArch64,PowerPC64LE架构的处理器上运行ClickHouse,您应该通过适当的配置调整从源代码构建ClickHouse。

  2. 可用安装方式

    • DEB安装

      建议使用Debian或Ubuntu的官方预编译deb软件包。运行以下命令来安装包:

        $ sudo apt-get install apt-transport-https ca-certificates dirmngr
        $ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv E0C56BD4
      
        $ echo "deb https://repo.clickhouse.tech/deb/stable/ main/" | sudo tee \
            /etc/apt/sources.list.d/clickhouse.list
        $ sudo apt-get update
      
        $ sudo apt-get install -y clickhouse-server clickhouse-client
      
        $ systemctl restart  clickhouse-server
        $ clickhouse-client
      
    • RPM安装

      推荐使用CentOS、RedHat和所有其他基于rpm的Linux发行版的官方预编译rpm包。

      首先,您需要添加官方存储库:

        $ sudo yum install yum-utils
        $ sudo rpm --import https://repo.clickhouse.tech/CLICKHOUSE-KEY.GPG
        $ sudo yum-config-manager --add-repo https://repo.clickhouse.tech/rpm/stable/x86_64
      

      然后运行命令安装:

        $ sudo yum install clickhouse-server clickhouse-client
      

      你也可以从这里手动下载安装包:下载。

        $ cp -rpv  /var/lib/clickhouse /data/clickhouse
      
        $ systemctl start clickhouse-server
        $ systemctl stop clickhouse-server
        $ systemctl status clickhouse-server
      
    • docker安装

      docker的安装这里就不说了,下面贴一个docker-compose.yml的内容。

        $ vim docker-compose.yml 
        version: '3'
        services:
        clickhouse:
            image: registry.docker-cn.com/yandex/clickhouse-server:20.8.16.20
            container_name: clickhouse
            restart: always
            volumes:
              - /data/clickhouse:/var/lib/clickhouse
            ulimits:
            nofile:
                soft: 262144
                hard: 262144
            ports:
              - 8123:8123
              - 9000:9000
            expose:
              - 8123
              - 9000
            logging:
            options:
                max-size: "100m"
                max-file: "5"
      
  3. 初始化

     $ mkdir -pv /data/clickhouse/{data,tmp,logs,format_schemas,user_files}
     $ chown -R clickhouse:clickhouse /data/clickhouse
    
     $ cp -pv /etc/clickhouse-server/config.xml{,.old}
     $ sudo systemctl start clickhouse-server
    
  4. 配置文件修改

    • /etc/clickhouse-server/的config.xml为ClickHouse核心配置文件,是服务全局设置。其中包含了一些默认配置,可以阅读其中注释了解其含义。对该文件内容的修改大多都需重启服务器才能生效。

      主要内容如下

        <?xml version="1.0"?>
        <yandex>
            <logger>
                <!-- 日志记录级别。可接受的值: trace, debug, information, warning, error -->
                <level>warning</level>
                <log>/data/clickhouse/logs/clickhouse-server.log</log>
                <errorlog>/data/clickhouse/logs/clickhouse-server.err.log</errorlog>
                <size>1000M</size>
                <count>10</count>
            </logger>
      
            <!-- 端口 -->
            <http_port>8123</http_port>
            <tcp_port>9000</tcp_port>
            <!-- 通过MySQL协议与客户端通信的端口 -->
            <mysql_port>9004</mysql_port>
            <!-- 在ClickHouse服务器之间交换数据的端口。 -->
            <interserver_http_port>9009</interserver_http_port>
      
            <!-- 其他服务器可以用来访问该服务器的主机名。如果省略,则其定义方法与hostname -f命令相同,该值必须全集群唯一。 -->
            <interserver_http_host>example.yandex.ru</interserver_http_host>
      
            <!-- 监听IP -->
            <listen_host>0.0.0.0</listen_host>
            <max_connections>64</max_connections>
            <keep_alive_timeout>3</keep_alive_timeout>
      
            <!-- 可用于Clickhouse的,服务器的总物理RAM量的比例。如果服务器尝试利用更多资源,则会将内存减少到适当的数量。-->
            <max_server_memory_usage_to_ram_ratio>0</max_server_memory_usage_to_ram_ratio>
      
            <!-- 最大并发查询数 -->
            <max_concurrent_queries>100</max_concurrent_queries>
      
            <!-- 全局线程池中的最大线程数。 -->
            <max_thread_pool_size>10000</max_thread_pool_size>
      
            <!-- 打开最大的文件数,默认最大值, 建议在Mac OS X中使用此选项,因为该getrlimit()函数返回的值不正确。 -->
            <!-- <max_open_files>262144</max_open_files> -->
      
            <!-- 表引擎从MergeTree使用的未压缩数据的缓存大小(以字节为单位,8G)。服务器有一个共享缓存,内存是按需分配的。如果启用,则使用高速缓存。在个别情况下,未压缩的缓存对于非常短的查询是有利的。 -->
            <uncompressed_cache_size>8589934592</uncompressed_cache_size>
      
            <!-- 标记缓存的大小,用于MergeTree系列的表中。  以字节为单位,共享服务器的缓存,并根据需要分配内存。缓存大小必须至少为5368709120(5G)。 -->
            <mark_cache_size>5368709120</mark_cache_size>
      
            <!-- 存储路径,建议设置ClickHouse数据存储目录使用独立的的磁盘或分区,便于优化性能。path 配置项路径需要使用 / 结尾,需要通过chown将该目录的所有者改为clickhouse:clickhouse 以保证读写权限。 -->
            <path>/data/clickhouse/</path>
      
            <!-- 用于处理大型查询的临时数据的路径 -->
            <tmp_path>/data/clickhouse/tmp/</tmp_path>
      
            <!-- 包含用户文件的目录。在表函数file()中使用。用于在指定文件中读取或写入数据。 -->
            <user_files_path>/data/clickhouse/user_files/</user_files_path>
      
            <!-- user配置 -->
            <users_config>users.xml</users_config>
            <default_profile>default</default_profile>
      
            <!--
                PARTITION BY expr: https://clickhouse.yandex/docs/en/table_engines/mergetree-family/custom_partitioning_key/
                Example:
                    event_date
                    toMonday(event_date) (将Date或DateTime向前取整到本周的星期一。)
                    toYYYYMM(event_date) (将Date或DateTime转换为包含年份和月份编号的UInt32类型的数字(YYYY * 100 + MM)。)
                    toStartOfHour(event_time) (将DateTime向前取整到当前小时的开始。)
            -->
            <!-- Query log. Used only for queries with setting log_queries = 1. -->
            <query_log>
                <database>system</database>
                <table>query_log</table>
                <partition_by>toYYYYMM(event_date)</partition_by>
                <flush_interval_milliseconds>7500</flush_interval_milliseconds>
            </query_log>
      
            <!-- Query thread log. Has information about all threads participated in query execution.
                Used only for queries with setting log_query_threads = 1. -->
            <query_thread_log>
                <database>system</database>
                <table>query_thread_log</table>
                <partition_by>toYYYYMM(event_date)</partition_by>
                <flush_interval_milliseconds>7500</flush_interval_milliseconds>
            </query_thread_log>
      
            <!-- Uncomment if use part log.
                Part log contains information about all actions with parts in MergeTree tables (creation, deletion, merges, downloads).
            <part_log>
                <database>system</database>
                <table>part_log</table>
                <flush_interval_milliseconds>7500</flush_interval_milliseconds>
            </part_log>
            -->
            
            <!-- Metric log contains rows with current values of ProfileEvents, CurrentMetrics collected with "collect_interval_milliseconds" interval. -->
            <metric_log>
                <database>system</database>
                <table>metric_log</table>
                <flush_interval_milliseconds>7500</flush_interval_milliseconds>
                <collect_interval_milliseconds>1000</collect_interval_milliseconds>
            </metric_log>
      
            <default_database>default</default_database>
      
            <!-- Perform mlockall after startup to lower first queries latency
                and to prevent clickhouse executable from being paged out under high IO load.
                Enabling this option is recommended but will lead to increased startup time for up to a few seconds.
            -->
            <mlock_executable>true</mlock_executable>
      
            <!-- Reallocate memory for machine code ("text") using huge pages. Highly experimental. -->
            <remap_executable>false</remap_executable>
      
            <remote_servers incl="clickhouse_remote_servers" />
            <zookeeper incl="zookeeper-servers" optional="true" />
            <macros incl="macros" optional="true" />
      
            <!-- 重新加载内置词典的时间间隔(以秒为单位),默认3600。可以在不重新启动服务器的情况下“即时”修改词典。 -->
            <builtin_dictionaries_reload_interval>3600</builtin_dictionaries_reload_interval>
      
            <!-- Maximum session timeout, in seconds. Default: 3600. -->
            <max_session_timeout>3600</max_session_timeout>
      
            <!-- Default session timeout, in seconds. Default: 60. -->
            <default_session_timeout>60</default_session_timeout>
      
            <!-- 控制大表的删除,默认的表drop保护,默认50G,达到该大小的表无法被直接drop删除。除非机器配置非常好,否则一般单表(数据集)达到50G(可能的数据量会在5-6亿行*100多列的数据量级)的数据量通常出于性能考虑会使用集群分片存储,不会达到限制。如果机器配置足够好且数据量较高,可能突破该限制,则需要禁用该保护,需要将该值设置为0 -->
            <max_table_size_to_drop>0</max_table_size_to_drop>
      
            <!-- 与上一配置类似,但针对的是比表更低粒度的partition。可参考上一配置修改。
            <!-- <max_partition_size_to_drop>0</max_partition_size_to_drop> -->
      
            <include_from>/etc/clickhouse-server/metrika.xml</include_from>
      
            <!-- 如果您希望数据压缩更好30-100%,请取消注释。如果您刚开始使用ClickHouse,请不要这样做。 -->
            <!--
            <compression>
                <!-- Set of variants. Checked in order. Last matching case wins. If nothing matches, lz4 will be used. 压缩算法lz4压缩比zstd快, 更占磁盘 -->
                <case>
                    <!- - Conditions. All must be satisfied. Some conditions may be omitted. - ->
                    <min_part_size>10000000000</min_part_size>        <!- - Min part size in bytes. - ->
                    <min_part_size_ratio>0.01</min_part_size_ratio>   <!- - Min size of part relative to whole table size. - ->
      
                    <!- - What compression method to use. - ->
                    <method>zstd</method>
                </case>
            </compression>
            -->
      
            <!-- Serve endpoint for Prometheus monitoring. -->
            <!--
                endpoint - mertics path (relative to root, statring with "/")
                port - port to setup server. If not defined or 0 than http_port used
                metrics - send data from table system.metrics
                events - send data from table system.events
                asynchronous_metrics - send data from table system.asynchronous_metrics
                status_info - send data from different component from CH, ex: Dictionaries status
            -->
            <!--
            <prometheus>
                <endpoint>/metrics</endpoint>
                <port>9363</port>
      
                <metrics>true</metrics>
                <events>true</events>
                <asynchronous_metrics>true</asynchronous_metrics>
                <status_info>true</status_info>
            </prometheus>
            -->
      
            <send_crash_reports>
                <enabled>false</enabled>
                <anonymize>false</anonymize>
                <endpoint>https://6f33034cfe684dd7a3ab9875e57b1c8d@o388870.ingest.sentry.io/5226277</endpoint>
            </send_crash_reports>
        </yandex>
      
    • /etc/clickhouse-server/的users.xml (测试环境下,可以选择不配置,线上环境一定要修改密码)

      users.xml包含了用户相关设置。包含3部分:profiles,quotas及users。所有的用户位于users 节点下,默认包含一个default用户和一个readonly用户。每个用户需要关联一个profile和一个quota,并可以设置密码和网络访问控制。profiles下每个profile是一组用户级的设置,系统包含一个默认default profile,更改profile中的设置不需要重启。

      建议修改users.xml更改default用户密码,或修改default用户networks设置只允许特定机器访问,以防止了解ClickHouse地址后直接用默认用户名密码连接修改其内容。

        <?xml version="1.0"?>
        <yandex>
            <profiles>
                <default>
                    <!-- 单个查询的最大内存使用量,如果查询占用内存超过该值,查询会以失败结束。可以结合并发量和当前物理内存设置。 -->
                    <max_memory_usage>10000000000</max_memory_usage>
                    <!-- 如果需要使用max_bytes_before_external_group_by,建议将max_memory_usage设置为max_bytes_before_external_group_by大小的两倍。原因是在clickhouse中聚合分两个阶段:查询并且建立中间数据;合并中间数据 写磁盘在第一个阶段,如果无须写磁盘,clickhouse在第一个和第二个阶段需要使用相同的内存。 -->
                    <use_uncompressed_cache>0</use_uncompressed_cache>
                    <load_balancing>random</load_balancing>
                </default>
      
                <readonly>
                    <readonly>1</readonly>
                </readonly>
            </profiles>
      
            <users>
                <default>
                    <password></password>
                    <networks>
                        <ip>127.0.0.1</ip>
                    </networks>
                    <profile>default</profile>
                    <quota>default</quota>
      
                </default>
      
                <testuser>
                    <password_sha256_hex>b84b497ef......61239e1460</password_sha256_hex>
                    <networks>
                        <ip>::/0</ip>
                    </networks>
                    <profile>default</profile>
                    <quota>default</quota>
                </testuser>
            </users>
      
            <quotas>
                <default>
                    <interval>
                        <duration>3600</duration>
                        <queries>0</queries>
                        <errors>0</errors>
                        <result_rows>0</result_rows>
                        <read_rows>0</read_rows>
                        <execution_time>0</execution_time>
                    </interval>
                </default>
            </quotas>
        </yandex>
      
    • 确认设置

      对于users.xml profile中的修改设置,可以通过客户端连接后,执行SQL查询system.settings 表确认(查看已更改的设置):

          select * from system.settings where changed
      
  5. 启动

     $ systemctl restart  clickhouse-server
    

ClickHouse集群环境搭建

  • 前提:在每一台服务器上已经安装好clickhouse单机版,同时zookeeper集群已经安装完成

  • 在每一台服务器上创建metrika.xml文件

    clickhouse_remote_servers 集群名称,可随意定义, 这里共设置3个分片,每个分片只有1个副本

      $ vim /etc/clickhouse-server/metrika.xml
    
          <yandex>
              <!-- 集群配置 -->
              <zookeeper-servers>
                  <node index="1">
                      <host>zk01</host>
                      <port>2181</port>
                  </node>
                  <node index="2">
                      <host>zk02</host>
                      <port>2182</port>
                  </node>
                  <node index="3">
                      <host>zk03</host>
                      <port>2183</port>
                  </node>
              </zookeeper-servers>
    
              <clickhouse_remote_servers>
                  <ck_cluster>
                      <shard>
                          <weight>1</weight>
                          <!-- false代表一次性写入所有副本,true表示写入其中一个副本,配合zk来进行数据复制 -->
                          <internal_replication>true</internal_replication>
                          <replica>
                              <host>ck01</host>
                              <port>9000</port>
                          </replica>
                          <replica>
                              <host>ck02</host>
                              <port>9000</port>
                          </replica>
                      </shard>
                      <shard>
                          <weight>1</weight>
                          <internal_replication>true</internal_replication>
                          <replica>
                              <host>ck02</host>
                              <port>9000</port>
                          </replica>
                          <replica>
                              <host>ck03</host>
                              <port>9000</port>
                          </replica>
                      </shard>
                      <shard>
                          <weight>1</weight>
                          <internal_replication>true</internal_replication>
                          <replica>
                              <host>ck03</host>
                              <port>9000</port>
                          </replica>
                          <replica>
                              <host>ck01</host>
                              <port>9000</port>
                          </replica>
                      </shard>
                  </ck_cluster>
              </clickhouse_remote_servers>
    
              <macros>
                  <!--layer 指定我们的集群标志,或者使用cluster关键字-->
                  <layer>ck_cluster</layer>
                  <!--分片ID, 指定的是集群分片信息中的配置,同一分片内的副本配置相同的分ID-->
                  <shard>01</shard>
                   <!--当前节点主机名-->
                  <replica>ck01</replica>
              </macros>
    
              <networks>
                  <ip>::/0</ip>
              </networks>
          </yandex>
    
  • 重启ClickHouse-server

      $ sudo systemctl restart  clickhouse-server  
    
  • 测试

    可以看到ck_cluster就是我们定义的集群名称,一共有三个分片,每个分片有一份数据。剩下的为配置文件默认自带的集群配置.

      $ sudo clickhouse-client -m
    
          ClickHouse client version 20.8.3.18.
          Connecting to localhost:9000 as user default.
          Connected to ClickHouse server version 20.8.3 revision 54438.
    
          ck01 :) select * from system.clusters;
    
          ┌─cluster────────────┬─shard_num─┬─shard_weight─┬─replica_num─┬─host_name─┬─host_address────┬─port─┬─is_local|
          │ ck_cluster         │         1 │            1 │           1 │ ck01      │ 192.168.100.161 │ 9000 │       1 │
          │ ck_cluster         │         2 │            1 │           1 │ ck02      │ 192.168.100.162 │ 9000 │       0 │
          │ ck_cluster         │         3 │            1 │           1 │ ck03      │ 192.168.100.163 │ 9000 │       0 │
          ......
    
          ck01 :)  select * from system.zookeeper where path = '/';
    
          ┌─name───────┬─value─┬──────czxid─┬──────mzxid─┬───────────────ctime─┬───────────────mtime─┬─version─┬─cversion─┬─aversion─┬
          │ zookeeper  │       │          0 │          0 │ 1970-01-01 08:00:00 │ 1970-01-01 08:00:00 │       0 │       -2 │        0 │
          │ clickhouse │       │ 4371612197 │ 4371612197 │ 2021-04-06 19:43:25 │ 2021-04-06 19:43:25 │       0 │        1 │        0 │ 
          └────────────┴───────┴────────────┴────────────┴─────────────────────┴─────────────────────┴─────────┴──────────┴──────────┴
    

    在三个节点上创建数据库cktest以及数据表replicatedTest,engine定义为ReplicatedMergeTree,例如

          ck01 :) create database cktest;
    
          ck01 :) create table cktest.replicatedTest(id Int16)
          engine=ReplicatedMergeTree('/clickhouse/tables/{shard}/replicatedTest','{replica}')
          order by id;
    

    随机选取一台插入数据,例如:

          ck01 :) insert into cktest.replicatedTest values(1);
    

    随机选取一台查询数据,例如:

          ck03 :) select * from cktest.replicatedTest;
    

文档参考

http://jackpgao.github.io/2017/12/13/ClickHouse-Cluster-Beginning-to-End/

https://github.com/sparkthu/clickhouse-doc-cn

http://blog.olei.me/2018/01/11/clickhouse%E5%88%9D%E5%AD%A6/

https://developer.aliyun.com/article/780145

https://my.oschina.net/merryyou/blog/4761102

https://blog.csdn.net/qq_35423190/article/details/109752743

https://blog.csdn.net/qq_35423190/article/details/109726587