网络中关于结合clickhouse、springboot以及mybatisPlus连接集群的文章较为稀缺,多数文章采用demo性质的jdbc。目前,mybatisPlus与springboot更适合大众开发,虽然操作简便,以下内容供大家参考。首先,在pom.xml中添加以下依赖:com.clickhouse.clickhouse-jdbc 0.3.2截至2023年9月20日,根据网上信息,高于此版本的clickhouse-jdbc尚不稳定,因此不推荐使用。同时,也不推荐使用旧版的ru.yandex.clickhouse。配置和config类在此不做展示,直接展示dataSource部分。package com.qihoo.vis.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import ru.yandex.clickhouse.BalancedClickhouseDataSource;import ru.yandex.clickhouse.settings.ClickHouseProperties;import javax.annotation.Resource;/** * ck数据库连接配置 */@Configurationpublic class CkDatasourceConfig {@Resourceprivate CkConfig config;@Beanpublic BalancedClickhouseDataSource dataSource() {//这里的BalancedClickhouseDataSource是为分布式ck集群使用,对应的驱动是ru.yandex.clickhouse.ClickHouseDriver。官方推荐com.clickhouse.jdbc.ClickHouseDriver对应的dataSource是com.clickhouse.jdbc.ClickHouseDataSource无法使用集群ClickHouseProperties clickHouseProperties = new ClickHouseProperties();clickHouseProperties.setUser(config.getUsername());clickHouseProperties.setPassword(config.getPassword());if (config.getSocketTimeOut() != null) {clickHouseProperties.setSocketTimeout(config.getSocketTimeOut());}BalancedClickhouseDataSource balanced = new BalancedClickhouseDataSource(config.getUrl(), clickHouseProperties);balanced.actualize();return balanced;}}其中的可用地址需要定时调用balanced.actualize()来进行健康检查,维护可用节点列表,以便在连接时能够随机连接到集群的各个节点。package com.qihoo.vis.config;import lombok.extern.slf4j.Slf4j;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;import ru.yandex.clickhouse.BalancedClickhouseDataSource;import javax.annotation.Resource;import java.util.Date;/** * ck节点健康检查 */@Component@Slf4jpublic class CkHealthCheck {@Resourceprivate BalancedClickhouseDataSource balanced;/** * 使用定时器定时调用balanced.actualize()维护可用的ck节点 */@Scheduled(cron = "*/5 * * * * ?")public void refreshAvailable() {log.info("定时刷新ck可用地址开始:" + new Date());balanced.actualize();log.info("定时刷新ck可用地址结束:" + new Date());}}