Nacos 国产化数据库Kingbase适配(基于SPI,不使用第三方插件)

开发环境

系统环境:java version “1.8.0_40”
Project Settings Project:11
Project Settings Modules:Language Level:8
Apache Maven 3.8.1

源码下载

Nacos 版本

nacos 2.2.0
版本说明:
Nacos 从 2.2.0 版本开始,可通过 SPI 机制注入多数据源实现插件,并在引入对应数据源实现后,便可在 Nacos 启动时通过读取 application.properties 配置文件中 spring.datasource.platform 配置项选择加载对应多数据源插件.

Nacos下载地址

git clone https://github.com/alibaba/nacos.git

Nacos模块说明

[api]
接口定义/封装

[client]
nacos客户端模块。 接口实现,请求封装

[cmdb]
标签/元数据/业务实现

[nacos]
通用模块/工具类,内部声明了http的使用方式,和一下通用接口或者抽象类。

[config]
配置服务业务实现 ,nacos两大核心功能配置中心实现就在该模块中。

[core] 
spring集成/工具类 模块:核心处理模块。权限过滤器配置,权限注解实现,核心异常处理,监听器等。

[example]
使用示例

[style]
代码规范

[test]
测试用例

[auth]
权限管理模块:该模块实现了nacos的权限功能。

[consistency]
一致性模块,该模块实现了nacos的一致性。主要是针对服务发现的一致性,配置中心主要是通过数据库完成的一致性。

[console]
管理后台 控制台模块:该模块实现了nacos控制台的集成,将前端页面与后端集成到一起。

[console-ui]
前端页面:nacos前端控制器UI代码。

[distribution]
构建目录 分布式模块:其实该模块只是包装了一下console模块,并且提供了一下外部配置文件和常用脚本。

[istio]
网格模块:实现了nacos的istio。

[naming]
nacos服务治理的实现模块。

Nacos编译运行

1.在cmd中进入nacos文件夹

cd C:\myWork\dev_workspace\Git-Repo\alibaba\nacos

2.执行BUILDING 中的脚本

mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U

3.编译后的文件位置

.....\Git-Repo\nacos\Nacos\distribution\target

4.启动
默认是集群模式,所以如果没有配置,直接运行会报错。
window情况下:
处理方式一: 进入cmd 输入startup.cmd -m standalone即可成功启动

startup.cmd -m standalone

处理方式二: 编辑startup.cmd启动命令,将set MODE="cluster"变成set MODE=“standalone” 然后双击即可编辑startup.cmd启动命令
单机模式通常用于测试,或者简单使用,集群模式主要用于生产环境保证高可用。

数据库初始化

在nacos-distribution项目的conf下有MySQL的数据库初始化语句,需要在数据库里执行

kingbase数据库初始化

数据库设置

特殊设置: kingbase.conf , ‘’ null 的转换,不然应用会出现错误。
data/kingbase.conf文件中,默认为on

ora_input_emptystr_isnull = off

创建数据库

数据库名称:nacos_kingbase
字符集:utf-8/utf8_bin

nacos-kingbase.sql

CREATE TABLE "config_info" (
	"id" bigint AUTO_INCREMENT,
	"data_id" character varying(255 char) NOT NULL,
	"group_id" character varying(255 char) NULL,
	"content" text NOT NULL,
	"md5" character varying(32 char) NULL,
	"gmt_create" timestamp(0) without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
	"gmt_modified" timestamp(0) without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
	"src_user" text NULL,
	"src_ip" character varying(50 char) NULL,
	"app_name" character varying(128 char) NULL,
	"tenant_id" character varying(128 char) NULL DEFAULT NULL::varchar,
	"c_desc" character varying(256 char) NULL,
	"c_use" character varying(64 char) NULL,
	"effect" character varying(64 char) NULL,
	"type" character varying(64 char) NULL,
	"c_schema" text NULL,
	"encrypted_data_key" text  NULL,
	CONSTRAINT "PRIMARY_73F26186" PRIMARY KEY (id),
	CONSTRAINT "uk_configinfo_datagrouptenant_C827FEB8" UNIQUE (data_id, group_id, tenant_id)
);


-- "pig_config"."config_info_aggr" definition

-- Drop table

-- DROP TABLE "config_info_aggr";

CREATE TABLE "config_info_aggr" (
	"id" bigint AUTO_INCREMENT,
	"data_id" character varying(255 char) NOT NULL,
	"group_id" character varying(255 char) NOT NULL,
	"datum_id" character varying(255 char) NOT NULL,
	"content" text NOT NULL,
	"gmt_modified" timestamp(0) without time zone NOT NULL,
	"app_name" character varying(128 char) NULL,
	"tenant_id" character varying(128 char) NULL DEFAULT NULL::varchar,
	CONSTRAINT "PRIMARY_F787E5C0" PRIMARY KEY (id),
	CONSTRAINT "uk_configinfoaggr_datagrouptenantdatum_D10078D8" UNIQUE (data_id, group_id, tenant_id, datum_id)
);


-- "pig_config"."config_info_beta" definition

-- Drop table

-- DROP TABLE "config_info_beta";

CREATE TABLE "config_info_beta" (
	"id" bigint AUTO_INCREMENT,
	"data_id" character varying(255 char) NOT NULL,
	"group_id" character varying(128 char) NOT NULL,
	"app_name" character varying(128 char) NULL,
	"content" text NOT NULL,
	"beta_ips" character varying(1024 char) NULL,
	"md5" character varying(32 char) NULL,
	"gmt_create" timestamp(0) without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
	"gmt_modified" timestamp(0) without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
	"src_user" text NULL,
	"src_ip" character varying(50 char) NULL,
	"tenant_id" character varying(128 char) NULL DEFAULT NULL::varchar,
	"encrypted_data_key" text  NULL,
	CONSTRAINT "PRIMARY_E3F5B61F" PRIMARY KEY (id),
	CONSTRAINT "uk_configinfobeta_datagrouptenant_E4D7C681" UNIQUE (data_id, group_id, tenant_id)
);


-- "pig_config"."config_info_tag" definition

-- Drop table

-- DROP TABLE "config_info_tag";

CREATE TABLE "config_info_tag" (
	"id" bigint AUTO_INCREMENT,
	"data_id" character varying(255 char) NOT NULL,
	"group_id" character varying(128 char) NOT NULL,
	"tenant_id" character varying(128 char) NULL DEFAULT NULL::varchar,
	"tag_id" character varying(128 char) NOT NULL,
	"app_name" character varying(128 char) NULL,
	"content" text NOT NULL,
	"md5" character varying(32 char) NULL,
	"gmt_create" timestamp(0) without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
	"gmt_modified" timestamp(0) without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
	"src_user" text NULL,
	"src_ip" character varying(50 char) NULL,
	CONSTRAINT "PRIMARY_26447CE1" PRIMARY KEY (id),
	CONSTRAINT "uk_configinfotag_datagrouptenanttag_5CBEB0AC" UNIQUE (data_id, group_id, tenant_id, tag_id)
);


-- "pig_config"."config_tags_relation" definition

-- Drop table

-- DROP TABLE "config_tags_relation";

CREATE TABLE "config_tags_relation" (
	"id" bigint NOT NULL,
	"tag_name" character varying(128 char) NOT NULL,
	"tag_type" character varying(64 char) NULL,
	"data_id" character varying(255 char) NOT NULL,
	"group_id" character varying(128 char) NOT NULL,
	"tenant_id" character varying(128 char) NULL DEFAULT NULL::varchar,
	"nid" bigint AUTO_INCREMENT,
	CONSTRAINT "PRIMARY_82226084" PRIMARY KEY (nid),
	CONSTRAINT "uk_configtagrelation_configidtag_25395725" UNIQUE (id, tag_name, tag_type)
);
CREATE INDEX idx_tenant_id_4FB846F8 ON config_tags_relation USING btree (tenant_id);


-- "pig_config"."group_capacity" definition

-- Drop table

-- DROP TABLE "group_capacity";

CREATE TABLE "group_capacity" (
	"id" bigint AUTO_INCREMENT,
	"group_id" character varying(128 char) NOT NULL DEFAULT NULL::varchar,
	"quota" bigint NOT NULL DEFAULT 0,
	"usage" bigint NOT NULL DEFAULT 0,
	"max_size" bigint NOT NULL DEFAULT 0,
	"max_aggr_count" bigint NOT NULL DEFAULT 0,
	"max_aggr_size" bigint NOT NULL DEFAULT 0,
	"max_history_count" bigint NOT NULL DEFAULT 0,
	"gmt_create" timestamp(0) without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
	"gmt_modified" timestamp(0) without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
	CONSTRAINT "PRIMARY_D72B7E75" PRIMARY KEY (id),
	CONSTRAINT "uk_group_id_377325F2" UNIQUE (group_id)
);


-- "pig_config"."his_config_info" definition

-- Drop table

-- DROP TABLE "his_config_info";

CREATE TABLE "his_config_info" (
	"id" numeric NOT NULL,
	"nid" bigint AUTO_INCREMENT,
	"data_id" character varying(255 char) NOT NULL,
	"group_id" character varying(128 char) NOT NULL,
	"app_name" character varying(128 char) NULL,
	"content" text NOT NULL,
	"md5" character varying(32 char) NULL,
	"gmt_create" timestamp(0) without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
	"gmt_modified" timestamp(0) without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
	"src_user" text NULL,
	"src_ip" character varying(50 char) NULL,
	"op_type" character(10 char) NULL,
	"tenant_id" character varying(128 char) NULL DEFAULT NULL::varchar,
	"encrypted_data_key" text NULL,
	CONSTRAINT "PRIMARY_93A4DC6B" PRIMARY KEY (nid)
);
CREATE INDEX idx_did_8DE97C10 ON his_config_info USING btree (data_id);
CREATE INDEX idx_gmt_create_F3B3E5A1 ON his_config_info USING btree (gmt_create);
CREATE INDEX idx_gmt_modified_42DBB1BB ON his_config_info USING btree (gmt_modified);


-- "pig_config"."permissions" definition

-- Drop table

-- DROP TABLE "permissions";

CREATE TABLE "permissions" (
	"role" character varying(50 char) NOT NULL,
	"resource" character varying(255 char) NOT NULL,
	"action" character varying(8 char) NOT NULL,
	CONSTRAINT "uk_role_permission_9C323780" UNIQUE (role, resource, action)
);


-- "pig_config"."roles" definition

-- Drop table

-- DROP TABLE "roles";

CREATE TABLE "roles" (
	"username" character varying(50 char) NOT NULL,
	"role" character varying(50 char) NOT NULL,
	CONSTRAINT "idx_user_role_314C5701" UNIQUE (username, role)
);


-- "pig_config"."tenant_capacity" definition

-- Drop table

-- DROP TABLE "tenant_capacity";

CREATE TABLE "tenant_capacity" (
	"id" bigint AUTO_INCREMENT,
	"tenant_id" character varying(128 char) NOT NULL DEFAULT NULL::varchar,
	"quota" bigint NOT NULL DEFAULT 0,
	"usage" bigint NOT NULL DEFAULT 0,
	"max_size" bigint NOT NULL DEFAULT 0,
	"max_aggr_count" bigint NOT NULL DEFAULT 0,
	"max_aggr_size" bigint NOT NULL DEFAULT 0,
	"max_history_count" bigint NOT NULL DEFAULT 0,
	"gmt_create" timestamp(0) without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
	"gmt_modified" timestamp(0) without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
	CONSTRAINT "PRIMARY_F4CCC2AA" PRIMARY KEY (id),
	CONSTRAINT "uk_tenant_id_22935E1" UNIQUE (tenant_id)
);


-- "pig_config"."tenant_info" definition

-- Drop table

-- DROP TABLE "tenant_info";

CREATE TABLE "tenant_info" (
	"id" bigint AUTO_INCREMENT,
	"kp" character varying(128 char) NOT NULL,
	"tenant_id" character varying(128 char) NULL DEFAULT NULL::varchar,
	"tenant_name" character varying(128 char) NULL DEFAULT NULL::varchar,
	"tenant_desc" character varying(256 char) NULL,
	"create_source" character varying(32 char) NULL,
	"gmt_create" bigint NOT NULL,
	"gmt_modified" bigint NOT NULL,
	CONSTRAINT "PRIMARY_8B91ED1E" PRIMARY KEY (id),
	CONSTRAINT "uk_tenant_info_kptenantid_195888C1" UNIQUE (kp, tenant_id)
);
CREATE INDEX idx_tenant_id_ABB71DBA ON tenant_info USING btree (tenant_id);


-- "pig_config"."users" definition

-- Drop table

-- DROP TABLE "users";

CREATE TABLE "users" (
	"username" character varying(50 char) NOT NULL,
	"password" character varying(500 char) NOT NULL,
	"enabled" tinyint NOT NULL,
	CONSTRAINT "PRIMARY_1A6B23BE" PRIMARY KEY (username)
);

INSERT INTO "roles" ("username","role") VALUES
	 ('nacos','ROLE_ADMIN');

INSERT INTO "users" ("username","password","enabled") VALUES
	 ('nacos','$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu',1);

重新创建约束

删除表中的唯一约束, 重新创建。

重新创建约束

config_info:
alter table public.config_info add constraint uk_configinfo_datagrouptenant_C827FEB8 unique (data_id, group_id, tenant_id);


config_info_aggr:
alter table public.config_info_aggr add constraint uk_configinfoaggr_datagrouptenantdatum_D10078D8 unique (data_id, group_id, tenant_id, datum_id);

config_info_beta:
alter table public.config_info_beta add constraint uk_configinfobeta_datagrouptenant_E4D7C681 unique (data_id, group_id, tenant_id);
  
config_info_tag:
alter table public.config_info_tag add constraint uk_configinfotag_datagrouptenanttag_5CBEB0AC unique (data_id, group_id, tenant_id, tag_id); 

config_tags_relation:
alter table public.config_tags_relation add constraint uk_configtagrelation_configidtag_25395725 unique (id, tag_name, tag_type); 

group_capacity:
alter table public.group_capacity add constraint uk_group_id_377325F2 unique (group_id); 

permissions:
alter table public.permissions add constraint uk_role_permission_9C323780 unique (role, resource, action);  

roles:
alter table public.roles add constraint idx_user_role_314C5701 unique (username, role);  

tenant_capacity:
alter table public.tenant_capacity add constraint uk_tenant_id_22935E1 unique (tenant_id);   

tenant_info:
alter table public.tenant_info add constraint uk_tenant_info_kptenantid_195888C1 unique (kp, tenant_id);  

源码修改

增加依赖

1.Maven项目引入Kingbase驱动KingbaseES V8 R6

1、驱动下载

Java数据库驱动JDBC人大金仓也提供了支持,在官网中可以找到下载地址,下载完成后就可以在对于的目录中找到需要的驱动jar包了

https://kingbase.oss-cn-beijing.aliyuncs.com/KES_INTERFACE/jdbc/x86/jdbc-x86.zip

在这里插入图片描述

2、引入Maven
1.上传到我们的Maven仓库中

使用Maven的命令进行安装,指定maven配置文件, 不然会上传到默认仓库中。

mvn install:install-file -Dfile=C:\Users\wenbo\Downloads\kingbase-jdbc-x86\kingbase8-8.6.0.jar  --settings=C:\myWork\dev_env\maven-settings\settings.xml -DgroupId=com.kingbase8 -DartifactId=kingbase8 -Dversion=8.6.0 -Dpackaging=jar

执行后如图,就表示安装成功了
在这里插入图片描述

2.再将我们的Maven索引更新一下,以免出现无法识别的错误

在这里插入图片描述

3.POM文件依赖添加

依赖添加如下

 <dependencies>
        <dependency>
            <groupId>com.kingbase8</groupId>
            <artifactId>kingbase8</artifactId>
            <version>8.6.0</version>
        </dependency>
    </dependencies>

2.添加Kingbase插件

nacos-all pom.xml

<kingbase8.version>8.6.0</kingbase8.version>
  
<!--人大金仓数据库驱动-->  
<dependency>  
<groupId>com.kingbase8</groupId>  
<artifactId>kingbase8</artifactId>  
<version>${kingbase8.version}</version>  
</dependency>

nacos-config pom.xml

<!--人大金仓数据库驱动-->  
<dependency>  
<groupId>com.kingbase8</groupId>  
<artifactId>kingbase8</artifactId>

nacos-console pom.xml

<!--人大金仓数据库驱动-->  
<dependency>  
<groupId>com.kingbase8</groupId>  
<artifactId>kingbase8</artifactId>  
</dependency>

nacos-datasource-plugin

<!--人大金仓数据库驱动-->  
<dependency>  
<groupId>com.kingbase8</groupId>  
<artifactId>kingbase8</artifactId>  
</dependency>

应用改造

1.(nacos-config)PropertiesConstant.java

Path Form Source Root

com/alibaba/nacos/config/server/constant/PropertiesConstant.java

增加:

public static final String KINGBASE = "kingbase8";

2.(nacos-config)PropertyUtil.java#loadSetting

Path Form Source Root

com/alibaba/nacos/config/server/utils/PropertyUtil.java

修改loadSetting方法

private void loadSetting() {  
try {  
setNotifyConnectTimeout(Integer.parseInt(EnvUtil.getProperty(PropertiesConstant.NOTIFY_CONNECT_TIMEOUT,  
String.valueOf(notifyConnectTimeout))));  
LOGGER.info("notifyConnectTimeout:{}", notifyConnectTimeout);  
setNotifySocketTimeout(Integer.parseInt(EnvUtil.getProperty(PropertiesConstant.NOTIFY_SOCKET_TIMEOUT,  
String.valueOf(notifySocketTimeout))));  
LOGGER.info("notifySocketTimeout:{}", notifySocketTimeout);  
setHealthCheck(Boolean.parseBoolean(  
EnvUtil.getProperty(PropertiesConstant.IS_HEALTH_CHECK, String.valueOf(isHealthCheck))));  
LOGGER.info("isHealthCheck:{}", isHealthCheck);  
setMaxHealthCheckFailCount(Integer.parseInt(  
EnvUtil.getProperty(PropertiesConstant.MAX_HEALTH_CHECK_FAIL_COUNT,  
String.valueOf(maxHealthCheckFailCount))));  
LOGGER.info("maxHealthCheckFailCount:{}", maxHealthCheckFailCount);  
setMaxContent(  
Integer.parseInt(EnvUtil.getProperty(PropertiesConstant.MAX_CONTENT, String.valueOf(maxContent))));  
LOGGER.info("maxContent:{}", maxContent);  
// capacity management  
setManageCapacity(getBoolean(PropertiesConstant.IS_MANAGE_CAPACITY, isManageCapacity));  
setCapacityLimitCheck(getBoolean(PropertiesConstant.IS_CAPACITY_LIMIT_CHECK, isCapacityLimitCheck));  
setDefaultClusterQuota(getInt(PropertiesConstant.DEFAULT_CLUSTER_QUOTA, defaultClusterQuota));  
setDefaultGroupQuota(getInt(PropertiesConstant.DEFAULT_GROUP_QUOTA, defaultGroupQuota));  
setDefaultTenantQuota(getInt(PropertiesConstant.DEFAULT_TENANT_QUOTA, defaultTenantQuota));  
setDefaultMaxSize(getInt(PropertiesConstant.DEFAULT_MAX_SIZE, defaultMaxSize));  
setDefaultMaxAggrCount(getInt(PropertiesConstant.DEFAULT_MAX_AGGR_COUNT, defaultMaxAggrCount));  
setDefaultMaxAggrSize(getInt(PropertiesConstant.DEFAULT_MAX_AGGR_SIZE, defaultMaxAggrSize));  
setCorrectUsageDelay(getInt(PropertiesConstant.CORRECT_USAGE_DELAY, correctUsageDelay));  
setInitialExpansionPercent(getInt(PropertiesConstant.INITIAL_EXPANSION_PERCENT, initialExpansionPercent));  
// External data sources are used by default in cluster mode  
//修改以下逻辑:获得当前的platform,如果platform为mysql或Kingbase8,则设置使用外部数据库为true。
String platform = DatasourcePlatformUtil.getDatasourcePlatform("");  
boolean useExternalStorage = PropertiesConstant.MYSQL.equalsIgnoreCase(platform)  
||  
PropertiesConstant.KINGBASE.equalsIgnoreCase(platform);  
setUseExternalDB(useExternalStorage);  
//修改完成。

// must initialize after setUseExternalDB  
// This value is true in stand-alone mode and false in cluster mode  
// If this value is set to true in cluster mode, nacos's distributed storage engine is turned on  
// default value is depend on ${nacos.standalone}  
  
if (isUseExternalDB()) {  
setEmbeddedStorage(false);  
} else {  
boolean embeddedStorage =  
PropertyUtil.embeddedStorage || Boolean.getBoolean(PropertiesConstant.EMBEDDED_STORAGE);  
setEmbeddedStorage(embeddedStorage);  
  
// If the embedded data source storage is not turned on, it is automatically  
// upgraded to the external data source storage, as before  
if (!embeddedStorage) {  
setUseExternalDB(true);  
}  
}  
} catch (Exception e) {  
LOGGER.error("read application.properties failed", e);  
throw e;  
}  
}

3.(nacos-config)ExternalDataSourceProperties.java

Path Form Source Root

com/alibaba/nacos/config/server/service/datasource/ExternalDataSourceProperties.java

定义kingbase驱动常量

private static final String JDBC_DRIVER_NAME_KINGBASE = "com.kingbase8.Driver";

修改build方法

List<HikariDataSource> build(Environment environment, Callback<HikariDataSource> callback) {
//修改以下逻辑:获得当前配置的数据源DatasourcePlatform,如果为kingbase8,则设置使用kingbase驱动"com.kingbase8.Driver"。
String jdbcDriverName = JDBC_DRIVER_NAME_MYSQL;  
String dataSourceType = DatasourcePlatformUtil.getDatasourcePlatform("");  
// 获得配置的platform  
if (PropertiesConstant.KINGBASE.equalsIgnoreCase(dataSourceType)) {  
jdbcDriverName = JDBC_DRIVER_NAME_KINGBASE;  
} else {  
jdbcDriverName = JDBC_DRIVER_NAME_MYSQL;  
}  
//修改完成
System.out.println("[dwb] " + this.getClass().getName() + " [build] [ current jdbcDriverName] : " + jdbcDriverName);  
List<HikariDataSource> dataSources = new ArrayList<>();  
Binder.get(environment).bind("db", Bindable.ofInstance(this));  
Preconditions.checkArgument(Objects.nonNull(num), "db.num is null");  
Preconditions.checkArgument(CollectionUtils.isNotEmpty(user), "db.user or db.user.[index] is null");  
Preconditions.checkArgument(CollectionUtils.isNotEmpty(password), "db.password or db.password.[index] is null");  
for (int index = 0; index < num; index++) {  
int currentSize = index + 1;  
Preconditions.checkArgument(url.size() >= currentSize, "db.url.%s is null", index);  
DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(environment);  
if (StringUtils.isEmpty(poolProperties.getDataSource().getDriverClassName())) {  
poolProperties.setDriverClassName(jdbcDriverName);  
}  
poolProperties.setJdbcUrl(url.get(index).trim());  
poolProperties.setUsername(getOrDefault(user, index, user.get(0)).trim());  
poolProperties.setPassword(getOrDefault(password, index, password.get(0)).trim());  
HikariDataSource ds = poolProperties.getDataSource();  
if (StringUtils.isEmpty(ds.getConnectionTestQuery())) {  
ds.setConnectionTestQuery(TEST_QUERY);  
}  
dataSources.add(ds);  
callback.accept(ds);  
}  
Preconditions.checkArgument(CollectionUtils.isNotEmpty(dataSources), "no datasource available");  
return dataSources;  
}

4.(config-console)StartingApplicationListener.java(增加log日志)

Path Form Source Root

com/alibaba/nacos/core/listener/StartingApplicationListener.java

方法增加log,方便启动时观察使用的platform

private void judgeStorageMode(ConfigurableEnvironment env) {   
// External data sources are used by default in cluster mode  
String platform = this.getDatasourcePlatform(env);  
System.out.println("[dwb]" + this.getClass().getName() + "platform:" + platform);  
boolean useExternalStorage =  
!DEFAULT_DATASOURCE_PLATFORM.equalsIgnoreCase(platform) && !DERBY_DATABASE.equalsIgnoreCase(platform);  
// must initialize after setUseExternalDB  
// This value is true in stand-alone mode and false in cluster mode  
// If this value is set to true in cluster mode, nacos's distributed storage engine is turned on  
// default value is depend on ${nacos.standalone}  
  
if (!useExternalStorage) {  
boolean embeddedStorage = EnvUtil.getStandaloneMode() || Boolean.getBoolean("embeddedStorage");  
// If the embedded data source storage is not turned on, it is automatically  
// upgraded to the external data source storage, as before  
if (!embeddedStorage) {  
useExternalStorage = true;  
}  
}  
  
LOGGER.info("Nacos started successfully in {} mode. use {} storage current platform {}",  
System.getProperty(MODE_PROPERTY_KEY_STAND_MODE),  
useExternalStorage ? DATASOURCE_MODE_EXTERNAL : DATASOURCE_MODE_EMBEDDED, platform  
);  
}

5.(nacos-config)DatasourcePlatformUtil(增加log日志)

Path Form Source Root

com/alibaba/nacos/config/server/utils/DatasourcePlatformUtil.java

增加log,方便启动时观察传入参数及获得的platform

public static String getDatasourcePlatform(String defaultPlatform) {  
String platform = EnvUtil.getProperty(PropertiesConstant.DATASOURCE_PLATFORM_PROPERTY, defaultPlatform);  
if (StringUtils.isBlank(platform)) {  
platform = EnvUtil.getProperty(PropertiesConstant.DATASOURCE_PLATFORM_PROPERTY_OLD, defaultPlatform);  
}  
System.out.println("[dwb] " + DatasourcePlatformUtil.class.getName()  
+  
" [inputParam] : [" + defaultPlatform + "] [current platform] : " + platform);  
return platform;  
}

6.(nacos-console)application.properties

增加数据库连接配置
Path Form Source Root

application.properties

调整内容

#*************** Config Module Related Configurations ***************#  
### If use MySQL as datasource:  
#MySQL  
#spring.datasource.platform=mysql  
#db.num=1  
#db.url.0=jdbc:mysql://192.168.xx.xx:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC  
#db.user.0=root  
#db.password.0=xx
  
#Kingbase  
spring.datasource.platform=kingbase8  
db.num=1  
db.url.0=jdbc:kingbase8://192.168.xx.xx:54321/nacos_kingbase?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC  
db.user.0=xx  
db.password.0=xx

7.(nacos-distribution)application.properties

Path Form Source Root

distribution/conf/application.properties

application.properties

#*************** Config Module Related Configurations ***************#  
### If use MySQL as datasource:  
#MySQL  
#spring.datasource.platform=mysql  
#db.num=1  
#db.url.0=jdbc:mysql://192.168.xx.xx:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC  
#db.user.0=root  
#db.password.0=xx
  
#Kingbase  
spring.datasource.platform=kingbase8  
db.num=1  
db.url.0=jdbc:kingbase8://192.168.xx.xx:54321/nacos_kingbase?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC  
db.user.0=xx
db.password.0=xx

8.(nacos-plugin)下(nacos-datasource-plugin)模块基于SPI增加对kingbase的Mapper操作支持。

1.增加Mapper接口的Kingbase8实现
AbstractKingbaseMapper.java
/*  
 * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0  
 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */  
package com.alibaba.nacos.plugin.datasource.impl.kingbase8;  
  
import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper;  
  
import java.util.List;  
  
/**  
 * The kingbase8 implementation. * * @author dwb  
 **/
public abstract class AbstractKingbaseMapper extends AbstractMapper {  
  
    @Override  
    public String select(List<String> columns, List<String> where) {  
        StringBuilder sql = new StringBuilder("SELECT ");  
  
        for (int i = 0; i < columns.size(); i++) {  
            sql.append(columns.get(i));  
            if (i == columns.size() - 1) {  
                sql.append(" ");  
            } else {  
                sql.append(",");  
            }  
        }        sql.append("FROM ");  
        sql.append(getTableName());  
        sql.append(" ");  
  
        if (where.size() == 0) {  
            return sql.toString();  
        }  
  
        sql.append("WHERE ");  
        for (int i = 0; i < where.size(); i++) {  
            String column = where.get(i);  
  
            // 租户列特殊处理 避免前端传空字符串是Oracle查询不到数据  
            if ("tenant_id".equalsIgnoreCase(column)) {  
                sql.append("(");  
                sql.append(column).append(" = ").append("?");  
                sql.append(" OR ");  
                sql.append(column).append(" IS NULL ");  
                sql.append(")");  
            } else {  
                sql.append(column).append(" = ").append("?");  
            }  
  
            if (i != where.size() - 1) {  
                sql.append(" AND ");  
            }  
        }        return sql.toString();  
    }  
  
    @Override  
    public String update(List<String> columns, List<String> where) {  
        StringBuilder sql = new StringBuilder();  
        String method = "UPDATE ";  
        sql.append(method);  
        sql.append(getTableName()).append(" ").append("SET ");  
  
        for (int i = 0; i < columns.size(); i++) {  
            sql.append(columns.get(i)).append(" = ").append("?");  
            if (i != columns.size() - 1) {  
                sql.append(",");  
            }  
        }  
        if (where.size() == 0) {  
            return sql.toString();  
        }  
  
        sql.append(" WHERE ");  
  
        for (int i = 0; i < where.size(); i++) {  
            String column = where.get(i);  
            if ("tenant_id".equalsIgnoreCase(column)) {  
                sql.append("(");  
                sql.append(column).append(" = ").append("?");  
                sql.append(" OR ");  
                sql.append(column).append(" IS NULL ");  
                sql.append(")");  
            } else {  
                sql.append(column).append(" = ").append("?");  
            }  
            if (i != where.size() - 1) {  
                sql.append(" AND ");  
            }  
        }        return sql.toString();  
    }  
  
    @Override  
    public String delete(List<String> params) {  
        StringBuilder sql = new StringBuilder();  
        String method = "DELETE ";  
        sql.append(method).append("FROM ").append(getTableName()).append(" ").append("WHERE ");  
        for (int i = 0; i < params.size(); i++) {  
            String column = params.get(i);  
            if ("tenant_id".equalsIgnoreCase(column)) {  
                sql.append("(");  
                sql.append(column).append(" = ").append("?");  
                sql.append(" OR ");  
                sql.append(column).append(" IS NULL ");  
                sql.append(")");  
            } else {  
                sql.append(column).append(" = ").append("?");  
            }  
            if (i != params.size() - 1) {  
                sql.append("AND ");  
            }  
        }  
        return sql.toString();  
    }  
  
    @Override  
    public String count(List<String> where) {  
        StringBuilder sql = new StringBuilder();  
        String method = "SELECT ";  
        sql.append(method);  
        sql.append("COUNT(*) FROM ");  
        sql.append(getTableName());  
        sql.append(" ");  
  
        if (null == where || where.size() == 0) {  
            return sql.toString();  
        }  
  
        sql.append("WHERE ");  
        for (int i = 0; i < where.size(); i++) {  
            String column = where.get(i);  
            if ("tenant_id".equalsIgnoreCase(column)) {  
                sql.append("(");  
                sql.append(column).append(" = ").append("?");  
                sql.append(" OR ");  
                sql.append(column).append(" IS NULL ");  
                sql.append(")");  
            } else {  
                sql.append(column).append(" = ").append("?");  
            }  
            if (i != where.size() - 1) {  
                sql.append(" AND ");  
            }  
        }        return sql.toString();  
    }  
  
    /**  
     * .     * buildPaginationSql     *     * @param originalSql originalSql  
     * @param startRow    startRow  
     * @param pageSize    pageSize  
     * @return String  
     */    public String buildPaginationSql(String originalSql, int startRow, int pageSize) {  
        return "SELECT * FROM ( SELECT TMP2.* FROM (SELECT TMP.*, ROWNUM ROW_ID FROM ( " + originalSql + " ) TMP) "  
                +  
                "TMP2 WHERE ROWNUM <=" + (startRow + pageSize) + ") WHERE ROW_ID > " + startRow;  
    }  
  
    /**  
     * getTableName.     *     * @return String  
     */    @Override  
    public abstract String getTableName();  
  
    /**  
     * getDataSource.     *     * @return String  
     */    @Override  
    public abstract String getDataSource();  
  
}
ConfigInfoAggrMapperByKingbase
/*  
 * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0  
 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */  
package com.alibaba.nacos.plugin.datasource.impl.kingbase8;  
  
import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant;  
import com.alibaba.nacos.plugin.datasource.constants.TableConstant;  
import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoAggrMapper;  
  
import java.util.List;  
  
/**  
 * The kingbase8 implementation. * * @author dwb  
 **/
public class ConfigInfoAggrMapperByKingbase extends AbstractKingbaseMapper implements ConfigInfoAggrMapper {  
  
    @Override  
    public String batchRemoveAggr(List<String> datumList) {  
        final StringBuilder datumString = new StringBuilder();  
        for (String datum : datumList) {  
            datumString.append('\'').append(datum).append("',");  
        }  
        datumString.deleteCharAt(datumString.length() - 1);  
        return "DELETE FROM config_info_aggr WHERE data_id = ? AND group_id = ? "  
                +  
                "AND (tenant_id = ? OR tenant_id IS NULL) AND datum_id IN (" + datumString + ")";  
    }  
  
    @Override  
    public String aggrConfigInfoCount(int size, boolean isIn) {  
        StringBuilder sql = new StringBuilder("SELECT count(*) FROM config_info_aggr WHERE data_id = ?"  
                +  
                " AND group_id = ? AND (tenant_id = ? OR tenant_id IS NULL) AND datum_id");  
        if (isIn) {  
            sql.append(" IN (");  
        } else {  
            sql.append(" NOT IN (");  
        }  
        for (int i = 0; i < size; i++) {  
            if (i > 0) {  
                sql.append(", ");  
            }  
            sql.append('?');  
        }  
        sql.append(')');  
  
        return sql.toString();  
    }  
  
    @Override  
    public String findConfigInfoAggrIsOrdered() {  
        return "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM "  
                +  
                "config_info_aggr WHERE data_id = ? AND group_id = ? AND (tenant_id = ? OR tenant_id IS NULL) "  
                +  
                "ORDER BY datum_id";  
    }  
  
    @Override  
    public String findConfigInfoAggrByPageFetchRows(int startRow, int pageSize) {  
        String sql = "SELECT data_id,group_id,tenant_id,datum_id,app_name,content FROM config_info_aggr "  
                +  
                "WHERE data_id= ? AND "  
                +  
                "group_id= ? AND (tenant_id= ? OR tenant_id IS NULL) ORDER BY datum_id";  
        return buildPaginationSql(sql, startRow, pageSize);  
    }  
  
    @Override  
    public String findAllAggrGroupByDistinct() {  
        return "SELECT DISTINCT data_id, group_id, tenant_id FROM config_info_aggr";  
    }  
  
    @Override  
    public String getTableName() {  
        return TableConstant.CONFIG_INFO_AGGR;  
    }  
  
    @Override  
    public String getDataSource() {  
        return DataSourceConstant.KINGBASE;  
    }  
  
}
ConfigInfoBetaMapperByKingbase
/*  
 * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0  
 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */  
package com.alibaba.nacos.plugin.datasource.impl.kingbase8;  
  
import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant;  
import com.alibaba.nacos.plugin.datasource.constants.TableConstant;  
import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoBetaMapper;  
  
/**  
 * The kingbase8 implementation. * * @author dwb  
 **/
public class ConfigInfoBetaMapperByKingbase extends AbstractKingbaseMapper implements ConfigInfoBetaMapper {  
  
    @Override  
    public String updateConfigInfo4BetaCas() {  
        return "UPDATE config_info_beta SET content = ?,md5 = ?,beta_ips = ?,src_ip = ?,src_user = ?,gmt_modified = ?,app_name = ? "  
                + "WHERE data_id = ? AND group_id = ? AND (tenant_id = ? OR tenant_id IS NULL) AND (md5 = ? or md5 is null or md5 = '')";  
    }  
  
    @Override  
    public String findAllConfigInfoBetaForDumpAllFetchRows(int startRow, int pageSize) {  
        return " SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,beta_ips,encrypted_data_key "  
                + " FROM ( SELECT rownum ROW_ID,id FROM config_info_beta  WHERE  ROW_ID<=  " + (startRow + pageSize)  
                + " ORDER BY id )" + " g, config_info_beta t WHERE g.id = t.id AND g.ROW_ID >" + startRow;  
    }  
  
    @Override  
    public String getTableName() {  
        return TableConstant.CONFIG_INFO_BETA;  
    }  
  
    @Override  
    public String getDataSource() {  
        return DataSourceConstant.KINGBASE;  
    }  
  
}
ConfigInfoMapperByKingbase
/*  
 * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0  
 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */  
package com.alibaba.nacos.plugin.datasource.impl.kingbase8;  
  
import com.alibaba.nacos.common.utils.CollectionUtils;  
import com.alibaba.nacos.common.utils.StringUtils;  
import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant;  
import com.alibaba.nacos.plugin.datasource.constants.TableConstant;  
import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoMapper;  
  
import java.sql.Timestamp;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Map;  
  
/**  
 * The kingbase8 implementation. * * @author dwb  
 **/
public class ConfigInfoMapperByKingbase extends AbstractKingbaseMapper implements ConfigInfoMapper {  
  
    private static final String DATA_ID = "dataId";  
  
    private static final String GROUP = "group";  
  
    private static final String APP_NAME = "appName";  
  
    private static final String CONTENT = "content";  
  
    private static final String TENANT = "tenant";  
  
    @Override  
    public String findConfigMaxId() {  
        return "SELECT MAX(id) FROM config_info";  
    }  
  
    @Override  
    public String findAllDataIdAndGroup() {  
        return "SELECT DISTINCT data_id, group_id FROM config_info";  
    }  
  
    @Override  
    public String findConfigInfoByAppCountRows() {  
        return "SELECT count(*) FROM config_info WHERE (tenant_id LIKE ? OR tenant_id IS NULL) AND app_name= ?";  
    }  
  
    @Override  
    public String findConfigInfoByAppFetchRows(int startRow, int pageSize) {  
        String sql = "SELECT id,data_id,group_id,tenant_id,app_name,content FROM config_info"  
                + " WHERE (tenant_id LIKE ? OR tenant_id IS NULL) AND app_name= ?";  
        return buildPaginationSql(sql, startRow, pageSize);  
    }  
  
    @Override  
    public String configInfoLikeTenantCount() {  
        return "SELECT count(*) FROM config_info WHERE (tenant_id LIKE ? OR tenant_id IS NULL)";  
    }  
  
    @Override  
    public String getTenantIdList(int startRow, int pageSize) {  
        String sql = "SELECT tenant_id FROM config_info WHERE tenant_id IS NOT NULL GROUP BY tenant_id ";  
        return buildPaginationSql(sql, startRow, pageSize);  
    }  
  
    @Override  
    public String getGroupIdList(int startRow, int pageSize) {  
        String sql = "SELECT group_id FROM config_info WHERE tenant_id IS NULL GROUP BY group_id ";  
        return buildPaginationSql(sql, startRow, pageSize);  
    }  
  
    @Override  
    public String findAllConfigKey(int startRow, int pageSize) {  
        String sql = " SELECT id,data_id,group_id,app_name FROM config_info WHERE (tenant_id LIKE ? OR tenant_id IS NULL)  ORDER BY id ";  
        return buildPaginationSql(sql, startRow, pageSize);  
    }  
  
    @Override  
    public String findAllConfigInfoBaseFetchRows(int startRow, int pageSize) {  
        String sql = "SELECT id,data_id,group_id,content,md5 FROM  config_info  ORDER BY id  ";  
        return buildPaginationSql(sql, startRow, pageSize);  
    }  
  
    @Override  
    public String findAllConfigInfoFragment(int startRow, int pageSize) {  
        String sql = "SELECT id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,type,encrypted_data_key "  
                + "FROM config_info WHERE id > ? ORDER BY id ASC ";  
        return buildPaginationSql(sql, startRow, pageSize);  
    }  
  
    @Override  
    public String findChangeConfig() {  
        return "SELECT data_id, group_id, tenant_id, app_name, content, gmt_modified,encrypted_data_key "  
                + "FROM config_info WHERE gmt_modified >= ? AND gmt_modified <= ?";  
    }  
  
    @Override  
    public String findChangeConfigCountRows(Map<String, String> params, final Timestamp startTime,  
                                            final Timestamp endTime) {  
        final String tenant = params.get(TENANT);  
        final String dataId = params.get(DATA_ID);  
        final String group = params.get(GROUP);  
        final String appName = params.get(APP_NAME);  
        final String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;  
        final String sqlCountRows = "SELECT count(*) FROM config_info WHERE ";  
        String where = " 1=1 ";  
        if (!StringUtils.isBlank(dataId)) {  
            where += " AND data_id LIKE ? ";  
        }  
        if (!StringUtils.isBlank(group)) {  
            where += " AND group_id LIKE ? ";  
        }  
  
        if (!StringUtils.isBlank(tenantTmp)) {  
            where += " AND (tenant_id = ? OR tenant_id IS NULL) ";  
        }  
  
        if (!StringUtils.isBlank(appName)) {  
            where += " AND app_name = ? ";  
        }  
        if (startTime != null) {  
            where += " AND gmt_modified >=? ";  
        }  
        if (endTime != null) {  
            where += " AND gmt_modified <=? ";  
        }  
        return sqlCountRows + where;  
    }  
  
    @Override  
    public String findChangeConfigFetchRows(Map<String, String> params, final Timestamp startTime,  
                                            final Timestamp endTime, int startRow, int pageSize, long lastMaxId) {  
        final String tenant = params.get(TENANT);  
        final String dataId = params.get(DATA_ID);  
        final String group = params.get(GROUP);  
        final String appName = params.get(APP_NAME);  
        final String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;  
        final String sqlFetchRows = "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_modified FROM config_info WHERE ";  
        String where = " 1=1 ";  
        if (!StringUtils.isBlank(dataId)) {  
            where += " AND data_id LIKE ? ";  
        }  
        if (!StringUtils.isBlank(group)) {  
            where += " AND group_id LIKE ? ";  
        }  
  
        if (!StringUtils.isBlank(tenantTmp)) {  
            where += " AND (tenant_id = ? OR tenant_id IS NULL) ";  
        }  
  
        if (!StringUtils.isBlank(appName)) {  
            where += " AND app_name = ? ";  
        }  
        if (startTime != null) {  
            where += " AND gmt_modified >=? ";  
        }  
        if (endTime != null) {  
            where += " AND gmt_modified <=? ";  
        }  
  
        String sql = sqlFetchRows + where + " AND id > " + lastMaxId + " ORDER BY id ASC";  
        return buildPaginationSql(sql, 0, pageSize);  
    }  
  
    @Override  
    public String listGroupKeyMd5ByPageFetchRows(int startRow, int pageSize) {  
        String sql = "SELECT id,data_id,group_id,tenant_id,app_name,md5,type,gmt_modified,encrypted_data_key  config_info  ORDER BY id ";  
        return buildPaginationSql(sql, startRow, pageSize);  
    }  
  
    @Override  
    public String findAllConfigInfo4Export(List<Long> ids, Map<String, String> params) {  
        String tenant = params.get("tenant");  
        String tenantTmp = StringUtils.isBlank(tenant) ? StringUtils.EMPTY : tenant;  
        String sql = "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_create,gmt_modified,src_user,src_ip,"  
                + "c_desc,c_use,effect,c_schema,encrypted_data_key FROM config_info";  
        StringBuilder where = new StringBuilder(" WHERE ");  
        List<Object> paramList = new ArrayList<>();  
        if (!CollectionUtils.isEmpty(ids)) {  
            where.append(" id IN (");  
            for (int i = 0; i < ids.size(); i++) {  
                if (i != 0) {  
                    where.append(", ");  
                }  
                where.append('?');  
                paramList.add(ids.get(i));  
            }  
            where.append(") ");  
        } else {  
            where.append(" (tenant_id= ? OR tenant_id IS NULL)");  
            paramList.add(tenantTmp);  
            if (!StringUtils.isBlank(params.get(DATA_ID))) {  
                where.append(" AND data_id LIKE ? ");  
            }  
            if (StringUtils.isNotBlank(params.get(GROUP))) {  
                where.append(" AND group_id= ? ");  
            }  
            if (StringUtils.isNotBlank(params.get(APP_NAME))) {  
                where.append(" AND app_name= ? ");  
            }  
        }        return sql + where;  
    }  
  
    @Override  
    public String findConfigInfoBaseLikeCountRows(Map<String, String> params) {  
        final String sqlCountRows = "SELECT count(*) FROM config_info WHERE ";  
        String where = " 1=1 AND (tenant_id='' OR tenant_id IS NULL) ";  
  
        if (!StringUtils.isBlank(params.get(DATA_ID))) {  
            where += " AND data_id LIKE ? ";  
        }  
        if (!StringUtils.isBlank(params.get(GROUP))) {  
            where += " AND group_id LIKE ";  
        }  
        if (!StringUtils.isBlank(params.get(CONTENT))) {  
            where += " AND content LIKE ? ";  
        }  
        return sqlCountRows + where;  
    }  
  
    @Override  
    public String findConfigInfoBaseLikeFetchRows(Map<String, String> params, int startRow, int pageSize) {  
        final String sqlFetchRows = "SELECT id,data_id,group_id,tenant_id,content FROM config_info WHERE ";  
        String where = " 1=1 AND (tenant_id='' OR tenant_id IS NULL) ";  
        if (!StringUtils.isBlank(params.get(DATA_ID))) {  
            where += " AND data_id LIKE ? ";  
        }  
        if (!StringUtils.isBlank(params.get(GROUP))) {  
            where += " AND group_id LIKE ";  
        }  
        if (!StringUtils.isBlank(params.get(CONTENT))) {  
            where += " AND content LIKE ? ";  
        }  
        String sql = sqlFetchRows + where;  
        return buildPaginationSql(sql, startRow, pageSize);  
    }  
  
    @Override  
    public String findConfigInfo4PageCountRows(Map<String, String> params) {  
        final String appName = params.get(APP_NAME);  
        final String dataId = params.get(DATA_ID);  
        final String group = params.get(GROUP);  
        final String sqlCount = "SELECT count(*) FROM config_info";  
        StringBuilder where = new StringBuilder(" WHERE ");  
        where.append(" ( tenant_id= ?  or tenant_id is NULL )");  
        if (StringUtils.isNotBlank(dataId)) {  
            where.append(" AND data_id=? ");  
        }  
        if (StringUtils.isNotBlank(group)) {  
            where.append(" AND group_id=? ");  
        }  
        if (StringUtils.isNotBlank(appName)) {  
            where.append(" AND app_name=? ");  
        }  
        return sqlCount + where;  
    }  
  
    @Override  
    public String findConfigInfo4PageFetchRows(Map<String, String> params, int startRow, int pageSize) {  
        final String appName = params.get(APP_NAME);  
        final String dataId = params.get(DATA_ID);  
        final String group = params.get(GROUP);  
        final String sql = "SELECT id,data_id,group_id,tenant_id,app_name,content,type,encrypted_data_key FROM config_info";  
        StringBuilder where = new StringBuilder(" WHERE ");  
        where.append(" ( tenant_id= ?  or tenant_id is NULL ) ");  
        if (StringUtils.isNotBlank(dataId)) {  
            where.append(" AND data_id=? ");  
        }  
        if (StringUtils.isNotBlank(group)) {  
            where.append(" AND group_id=? ");  
        }  
        if (StringUtils.isNotBlank(appName)) {  
            where.append(" AND app_name=? ");  
        }  
        return buildPaginationSql(sql + where, startRow, pageSize);  
    }  
  
    @Override  
    public String findConfigInfoBaseByGroupFetchRows(int startRow, int pageSize) {  
        String sql = "SELECT id,data_id,group_id,content FROM config_info WHERE group_id=? AND ( tenant_id= ?  or tenant_id is NULL )";  
        return buildPaginationSql(sql, startRow, pageSize);  
    }  
  
    @Override  
    public String findConfigInfoLike4PageCountRows(Map<String, String> params) {  
        String dataId = params.get(DATA_ID);  
        String group = params.get(GROUP);  
        final String appName = params.get(APP_NAME);  
        final String content = params.get(CONTENT);  
        final String sqlCountRows = "SELECT count(*) FROM config_info";  
        StringBuilder where = new StringBuilder(" WHERE ");  
        where.append(" (tenant_id LIKE ? OR tenant_id IS NULL) ");  
        if (!StringUtils.isBlank(dataId)) {  
            where.append(" AND data_id LIKE ? ");  
        }  
        if (!StringUtils.isBlank(group)) {  
            where.append(" AND group_id LIKE ? ");  
        }  
        if (!StringUtils.isBlank(appName)) {  
            where.append(" AND app_name = ? ");  
        }  
        if (!StringUtils.isBlank(content)) {  
            where.append(" AND content LIKE ? ");  
        }  
        return sqlCountRows + where;  
    }  
  
    @Override  
    public String findConfigInfoLike4PageFetchRows(Map<String, String> params, int startRow, int pageSize) {  
        String dataId = params.get(DATA_ID);  
        String group = params.get(GROUP);  
        final String appName = params.get(APP_NAME);  
        final String content = params.get(CONTENT);  
        final String sqlFetchRows = "SELECT id,data_id,group_id,tenant_id,app_name,content,encrypted_data_key FROM config_info";  
        StringBuilder where = new StringBuilder(" WHERE ");  
        where.append(" (tenant_id LIKE ? OR tenant_id IS NULL) ");  
        if (!StringUtils.isBlank(dataId)) {  
            where.append(" AND data_id LIKE ? ");  
        }  
        if (!StringUtils.isBlank(group)) {  
            where.append(" AND group_id LIKE ? ");  
        }  
        if (!StringUtils.isBlank(appName)) {  
            where.append(" AND app_name = ? ");  
        }  
        if (!StringUtils.isBlank(content)) {  
            where.append(" AND content LIKE ? ");  
        }  
        return buildPaginationSql(sqlFetchRows + where, startRow, pageSize);  
    }  
  
    @Override  
    public String findAllConfigInfoFetchRows(int startRow, int pageSize) {  
        String sql = "SELECT id,data_id,group_id,tenant_id,app_name,content,md5 "  
                + " FROM  config_info WHERE (tenant_id LIKE ? OR tenant_id IS NULL) ORDER BY id ";  
        return buildPaginationSql(sql, startRow, pageSize);  
    }  
  
    @Override  
    public String findConfigInfosByIds(int idSize) {  
        StringBuilder sql = new StringBuilder(  
                "SELECT ID,data_id,group_id,tenant_id,app_name,content,md5 FROM config_info WHERE ");  
        sql.append("id IN (");  
        for (int i = 0; i < idSize; i++) {  
            if (i != 0) {  
                sql.append(", ");  
            }  
            sql.append('?');  
        }  
        sql.append(") ");  
        return sql.toString();  
    }  
  
    @Override  
    public String removeConfigInfoByIdsAtomic(int size) {  
        StringBuilder sql = new StringBuilder("DELETE FROM config_info WHERE ");  
        sql.append("id IN (");  
        for (int i = 0; i < size; i++) {  
            if (i != 0) {  
                sql.append(", ");  
            }  
            sql.append('?');  
        }  
        sql.append(") ");  
        return sql.toString();  
    }  
  
    @Override  
    public String updateConfigInfoAtomicCas() {  
        return "UPDATE config_info SET "  
                + "content=?, md5 = ?, src_ip=?,src_user=?,gmt_modified=?, app_name=?,c_desc=?,c_use=?,effect=?,type=?,c_schema=? "  
                + "WHERE data_id=? AND group_id=? AND (tenant_id=? OR tenant_id IS NULL) AND (md5=? OR md5 IS NULL OR md5='')";  
    }  
  
    @Override  
    public String getTableName() {  
        return TableConstant.CONFIG_INFO;  
    }  
  
    @Override  
    public String getDataSource() {  
        return DataSourceConstant.KINGBASE;  
    }  
  
}
ConfigInfoTagMapperByKingbase
/*  
 * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0  
 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */  
package com.alibaba.nacos.plugin.datasource.impl.kingbase8;  
  
import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant;  
import com.alibaba.nacos.plugin.datasource.constants.TableConstant;  
import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoTagMapper;  
  
/**  
 * The kingbase8 implementation. * * @author dwb  
 **/
public class ConfigInfoTagMapperByKingbase extends AbstractKingbaseMapper implements ConfigInfoTagMapper {  
  
    @Override  
    public String updateConfigInfo4TagCas() {  
        return "UPDATE config_info_tag SET content = ?, md5 = ?, src_ip = ?,src_user = ?,gmt_modified = ?"  
                +  
                ",app_name = ? " + "WHERE data_id = ? AND group_id = ? AND "  
                +  
                "(tenant_id = ? OR tenant_id IS NULL) AND tag_id = ? AND (md5 = ? OR md5 IS NULL OR md5 = '')";  
    }  
  
    @Override  
    public String findAllConfigInfoTagForDumpAllFetchRows(int startRow, int pageSize) {  
        return " SELECT t.id,data_id,group_id,tenant_id,tag_id,app_name,content,md5,gmt_modified "  
                +  
                " FROM (  SELECT id FROM config_info_tag WHERE  ROWNUM > " + startRow  
                +  
                " AND ROWNUM <=" + (startRow + pageSize) + "ORDER BY id   " + " ) "  
                +  
                "g, config_info_tag t  WHERE g.id = t.id  ";  
    }  
  
    @Override  
    public String getTableName() {  
        return TableConstant.CONFIG_INFO_TAG;  
    }  
  
    @Override  
    public String getDataSource() {  
        return DataSourceConstant.KINGBASE;  
    }  
  
}
ConfigTagsRelationMapperByKingbase
/*  
 * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0  
 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */  
package com.alibaba.nacos.plugin.datasource.impl.kingbase8;  
  
import com.alibaba.nacos.common.utils.StringUtils;  
import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant;  
import com.alibaba.nacos.plugin.datasource.constants.TableConstant;  
import com.alibaba.nacos.plugin.datasource.mapper.ConfigTagsRelationMapper;  
  
import java.util.Map;  
  
/**  
 * The kingbase8 implementation. * * @author dwb  
 **/
public class ConfigTagsRelationMapperByKingbase extends AbstractKingbaseMapper implements ConfigTagsRelationMapper {  
  
    @Override  
    public String findConfigInfo4PageCountRows(final Map<String, String> params, final int tagSize) {  
        final String appName = params.get("appName");  
        final String dataId = params.get("dataId");  
        final String group = params.get("group");  
        StringBuilder where = new StringBuilder(" WHERE ");  
        final String sqlCount = "SELECT count(*) FROM config_info  a LEFT JOIN config_tags_relation b ON a.id=b.id";  
        where.append(" (a.tenant_id=? OR a.tenant_id IS NULL)");  
        if (StringUtils.isNotBlank(dataId)) {  
            where.append(" AND a.data_id=? ");  
        }  
        if (StringUtils.isNotBlank(group)) {  
            where.append(" AND a.group_id=? ");  
        }  
        if (StringUtils.isNotBlank(appName)) {  
            where.append(" AND a.app_name=? ");  
        }  
        where.append(" AND b.tag_name IN (");  
        for (int i = 0; i < tagSize; i++) {  
            if (i != 0) {  
                where.append(", ");  
            }  
            where.append('?');  
        }  
        where.append(") ");  
        return sqlCount + where;  
    }  
  
    @Override  
    public String findConfigInfo4PageFetchRows(Map<String, String> params, int tagSize, int startRow, int pageSize) {  
        final String appName = params.get("appName");  
        final String dataId = params.get("dataId");  
        final String group = params.get("group");  
        StringBuilder where = new StringBuilder(" WHERE ");  
        final String sql = "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info "  
                +  
                " a LEFT JOIN " + "config_tags_relation b ON a.id=b.id";  
  
        where.append("( a.tenant_id=? OR tenant_id IS NULL)");  
  
        if (StringUtils.isNotBlank(dataId)) {  
            where.append(" AND a.data_id=? ");  
        }  
        if (StringUtils.isNotBlank(group)) {  
            where.append(" AND a.group_id=? ");  
        }  
        if (StringUtils.isNotBlank(appName)) {  
            where.append(" AND a.app_name=? ");  
        }  
  
        where.append(" AND b.tag_name IN (");  
        for (int i = 0; i < tagSize; i++) {  
            if (i != 0) {  
                where.append(", ");  
            }  
            where.append('?');  
        }  
        where.append(") ");  
        return sql + where + " AND  ROWNUM > " + sql + " AND ROWNUM <= " + (startRow + pageSize);  
    }  
  
    @Override  
    public String findConfigInfoLike4PageCountRows(final Map<String, String> params, int tagSize) {  
        final String appName = params.get("appName");  
        final String content = params.get("content");  
        final String dataId = params.get("dataId");  
        final String group = params.get("group");  
        StringBuilder where = new StringBuilder(" WHERE ");  
        final String sqlCountRows = "SELECT count(*) FROM config_info  a LEFT JOIN config_tags_relation b ON a.id=b.id ";  
  
        where.append(" a.(tenant_id LIKE ? OR tenant_id IS NULL) ");  
        if (!StringUtils.isBlank(dataId)) {  
            where.append(" AND a.data_id LIKE ? ");  
        }  
        if (!StringUtils.isBlank(group)) {  
            where.append(" AND a.group_id LIKE ? ");  
        }  
        if (!StringUtils.isBlank(appName)) {  
            where.append(" AND a.app_name = ? ");  
        }  
        if (!StringUtils.isBlank(content)) {  
            where.append(" AND a.content LIKE ? ");  
        }  
  
        where.append(" AND b.tag_name IN (");  
        for (int i = 0; i < tagSize; i++) {  
            if (i != 0) {  
                where.append(", ");  
            }  
            where.append('?');  
        }  
        where.append(") ");  
        return sqlCountRows + where;  
    }  
  
    @Override  
    public String findConfigInfoLike4PageFetchRows(final Map<String, String> params, int tagSize, int startRow, int pageSize) {  
        final String appName = params.get("appName");  
        final String content = params.get("content");  
        final String dataId = params.get("dataId");  
        final String group = params.get("group");  
        StringBuilder where = new StringBuilder(" WHERE ");  
        final String sqlFetchRows = "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content "  
                +  
                "FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id ";  
  
        where.append(" a.(tenant_id LIKE ? OR tenant_id IS NULL) ");  
        if (!StringUtils.isBlank(dataId)) {  
            where.append(" AND a.data_id LIKE ? ");  
        }  
        if (!StringUtils.isBlank(group)) {  
            where.append(" AND a.group_id LIKE ? ");  
        }  
        if (!StringUtils.isBlank(appName)) {  
            where.append(" AND a.app_name = ? ");  
        }  
        if (!StringUtils.isBlank(content)) {  
            where.append(" AND a.content LIKE ? ");  
        }  
  
        where.append(" AND b.tag_name IN (");  
        for (int i = 0; i < tagSize; i++) {  
            if (i != 0) {  
                where.append(", ");  
            }  
            where.append('?');  
        }  
        where.append(") ");  
        return sqlFetchRows + where + " AND ROWNUM > " + startRow + " AND ROWNUM <= " + (startRow + pageSize);  
    }  
  
    @Override  
    public String getTableName() {  
        return TableConstant.CONFIG_TAGS_RELATION;  
    }  
  
    @Override  
    public String getDataSource() {  
        return DataSourceConstant.KINGBASE;  
    }  
  
}
GroupCapacityMapperByKingbase
/*  
 * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0  
 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */  
package com.alibaba.nacos.plugin.datasource.impl.kingbase8;  
  
import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant;  
import com.alibaba.nacos.plugin.datasource.constants.TableConstant;  
import com.alibaba.nacos.plugin.datasource.mapper.GroupCapacityMapper;  
  
/**  
 * The kingbase8 implementation. * * @author dwb  
 **/
public class GroupCapacityMapperByKingbase extends AbstractKingbaseMapper implements GroupCapacityMapper {  
  
    @Override  
    public String insertIntoSelect() {  
        return "INSERT INTO group_capacity (group_id, quota, `usage`, `max_size`, max_aggr_count, " + "max_aggr_size,"  
                + "gmt_create," + " gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? FROM config_info";  
    }  
  
    @Override  
    public String insertIntoSelectByWhere() {  
        return "INSERT INTO group_capacity (group_id, quota,`usage`, `max_size`, max_aggr_count, max_aggr_size," + " "  
                + "gmt_create," + " gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? " + "FROM config_info WHERE "  
                + "group_id=? AND tenant_id = ''";  
    }  
  
    @Override  
    public String incrementUsageByWhereQuotaEqualZero() {  
        return "UPDATE group_capacity SET `usage` = `usage` + 1, gmt_modified = ? WHERE group_id = ? " + "AND `usage`"  
                + " < ? AND quota = 0";  
    }  
  
    @Override  
    public String incrementUsageByWhereQuotaNotEqualZero() {  
        return "UPDATE group_capacity SET `usage` = `usage` + 1, gmt_modified = ? WHERE group_id = ? AND `usage` < " + "quota AND quota != 0";  
    }  
  
    @Override  
    public String incrementUsageByWhere() {  
        return "UPDATE group_capacity SET `usage` = `usage` + 1, gmt_modified = ? WHERE group_id = ?";  
    }  
  
    @Override  
    public String decrementUsageByWhere() {  
        return "UPDATE group_capacity SET `usage` = `usage` - 1, gmt_modified = ? WHERE group_id = ? AND `usage` > 0";  
    }  
  
    @Override  
    public String updateUsage() {  
        return "UPDATE group_capacity SET `usage` = (SELECT count(*) FROM config_info), " + "gmt_modified = ? WHERE "  
                + "group_id = ?";  
    }  
  
    @Override  
    public String updateUsageByWhere() {  
        return "UPDATE group_capacity SET `usage` = (SELECT count(*) FROM config_info WHERE group_id=? " + "AND "  
                + "tenant_id = '')," + " gmt_modified = ? WHERE group_id= ?";  
    }  
  
    @Override  
    public String selectGroupInfoBySize() {  
        return "SELECT id, group_id FROM group_capacity WHERE id > ? ROWNUM > ?";  
    }  
  
    @Override  
    public String getTableName() {  
        return TableConstant.GROUP_CAPACITY;  
    }  
  
    @Override  
    public String getDataSource() {  
        return DataSourceConstant.KINGBASE;  
    }  
  
}
HistoryConfigInfoMapperByKingbase
/*  
 * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0  
 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */  
package com.alibaba.nacos.plugin.datasource.impl.kingbase8;  
  
import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant;  
import com.alibaba.nacos.plugin.datasource.constants.TableConstant;  
import com.alibaba.nacos.plugin.datasource.mapper.HistoryConfigInfoMapper;  
  
/**  
 * The kingbase8 implementation. * * @author dwb  
 **/
public class HistoryConfigInfoMapperByKingbase extends AbstractKingbaseMapper implements HistoryConfigInfoMapper {  
  
    @Override  
    public String removeConfigHistory() {  
        return "DELETE FROM his_config_info WHERE gmt_modified < ? AND ROWNUM > ?";  
    }  
  
    @Override  
    public String findConfigHistoryCountByTime() {  
        return "SELECT count(*) FROM his_config_info WHERE gmt_modified < ?";  
    }  
  
    @Override  
    public String findDeletedConfig() {  
        return "SELECT DISTINCT data_id, group_id, tenant_id FROM his_config_info WHERE op_type = 'D' AND gmt_modified >= ? AND gmt_modified <= ?";  
    }  
  
    @Override  
    public String findConfigHistoryFetchRows() {  
        return "SELECT nid,data_id,group_id,tenant_id,app_name,src_ip,src_user,op_type,"  
                +  
                "gmt_create,gmt_modified FROM his_config_info " + "WHERE data_id = ? "  
                +  
                "AND group_id = ? AND (tenant_id = ? OR tenant_id IS NULL) ORDER BY nid DESC";  
    }  
  
    @Override  
    public String detailPreviousConfigHistory() {  
        return "SELECT nid,data_id,group_id,tenant_id,app_name,content,md5,src_user,src_ip,op_type,"  
                +  
                "gmt_create,gmt_modified " + "FROM his_config_info WHERE nid = "  
                +  
                "(SELECT max(nid) FROM his_config_info WHERE id = ?) ";  
    }  
  
    @Override  
    public String getTableName() {  
        return TableConstant.HIS_CONFIG_INFO;  
    }  
  
    @Override  
    public String getDataSource() {  
        return DataSourceConstant.KINGBASE;  
    }  
  
}
TenantCapacityMapperByKingbase
/*  
 * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0  
 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */  
package com.alibaba.nacos.plugin.datasource.impl.kingbase8;  
  
import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant;  
import com.alibaba.nacos.plugin.datasource.constants.TableConstant;  
import com.alibaba.nacos.plugin.datasource.mapper.TenantCapacityMapper;  
  
/**  
 * The kingbase8 implementation. * * @author dwb  
 **/
public class TenantCapacityMapperByKingbase extends AbstractKingbaseMapper implements TenantCapacityMapper {  
  
    @Override  
    public String incrementUsageWithDefaultQuotaLimit() {  
        return "UPDATE tenant_capacity SET `usage` = `usage` + 1, gmt_modified = ?" + " WHERE ((tenant_id = ? OR "  
                +  
                "tenant_id IS NULL) OR tenant_id IS NULL) AND `usage` <" + " ? AND quota = 0";  
    }  
  
    @Override  
    public String incrementUsageWithQuotaLimit() {  
        return "UPDATE tenant_capacity SET `usage` = `usage` + 1, gmt_modified = ? " + "WHERE (tenant_id = ? OR "  
                +  
                "tenant_id IS NULL) AND `usage` < " + "quota AND quota != 0";  
    }  
  
    @Override  
    public String incrementUsage() {  
        return "UPDATE tenant_capacity SET `usage` = `usage` + 1, gmt_modified = ? " + "WHERE (tenant_id = ? OR "  
                +  
                "tenant_id IS NULL)";  
    }  
  
    @Override  
    public String decrementUsage() {  
        return "UPDATE tenant_capacity SET `usage` = `usage` - 1, gmt_modified = ? " + "WHERE (tenant_id = ? OR "  
                +  
                "tenant_id IS NULL) AND `usage` > 0";  
    }  
  
    @Override  
    public String correctUsage() {  
        return "UPDATE tenant_capacity SET `usage` = (SELECT count(*) FROM config_info WHERE (tenant_id = ? OR "  
                +  
                "tenant_id IS NULL)), " + "gmt_modified = ? WHERE (tenant_id = ? OR tenant_id IS NULL)";  
    }  
  
    @Override  
    public String getCapacityList4CorrectUsage() {  
        return "SELECT id, tenant_id FROM tenant_capacity WHERE id> AND  ROWNUM > ?";  
    }  
  
    @Override  
    public String insertTenantCapacity() {  
        return "INSERT INTO tenant_capacity (tenant_id, quota, `usage`, `max_size`, max_aggr_count, max_aggr_size, "  
                +  
                "gmt_create, gmt_modified) SELECT ?, ?, count(*), ?, ?, ?, ?, ? "  
                +  
                "FROM config_info WHERE tenant_id=? OR tenant_id IS NULL;";  
    }  
  
    @Override  
    public String getTableName() {  
        return TableConstant.TENANT_CAPACITY;  
    }  
  
    @Override  
    public String getDataSource() {  
        return DataSourceConstant.KINGBASE;  
    }  
  
}
TenantInfoMapperByKingbase
/*  
 * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0  
 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */  
package com.alibaba.nacos.plugin.datasource.impl.kingbase8;  
  
import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant;  
import com.alibaba.nacos.plugin.datasource.constants.TableConstant;  
import com.alibaba.nacos.plugin.datasource.mapper.TenantInfoMapper;  
  
/**  
 * The kingbase8 implementation. * * @author dwb  
 **/
public class TenantInfoMapperByKingbase extends AbstractKingbaseMapper implements TenantInfoMapper {  
  
    @Override  
    public String getTableName() {  
        return TableConstant.TENANT_INFO;  
    }  
  
    @Override  
    public String getDataSource() {  
        return DataSourceConstant.KINGBASE;  
    }  
  
}
2.配置SPI实现类

修改com.alibaba.nacos.plugin.datasource.mapper.Mapper文件
Path From Source Root

META-INF/services/com.alibaba.nacos.plugin.datasource.mapper.Mapper

增加上述实现类内容

#  
# Copyright 1999-2022 Alibaba Group Holding Ltd.  
#  
# Licensed under the Apache License, Version 2.0 (the "License");  
# you may not use this file except in compliance with the License.  
# You may obtain a copy of the License at  
#  
#      http://www.apache.org/licenses/LICENSE-2.0  
#  
# Unless required by applicable law or agreed to in writing, software  
# distributed under the License is distributed on an "AS IS" BASIS,  
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
# See the License for the specific language governing permissions and  
# limitations under the License.  
#  
  
com.alibaba.nacos.plugin.datasource.impl.mysql.ConfigInfoAggrMapperByMySql  
com.alibaba.nacos.plugin.datasource.impl.mysql.ConfigInfoBetaMapperByMySql  
com.alibaba.nacos.plugin.datasource.impl.mysql.ConfigInfoMapperByMySql  
com.alibaba.nacos.plugin.datasource.impl.mysql.ConfigInfoTagMapperByMySql  
com.alibaba.nacos.plugin.datasource.impl.mysql.ConfigTagsRelationMapperByMySql  
com.alibaba.nacos.plugin.datasource.impl.mysql.HistoryConfigInfoMapperByMySql  
com.alibaba.nacos.plugin.datasource.impl.mysql.TenantInfoMapperByMySql  
com.alibaba.nacos.plugin.datasource.impl.mysql.TenantCapacityMapperByMySql  
com.alibaba.nacos.plugin.datasource.impl.mysql.GroupCapacityMapperByMysql  
  
com.alibaba.nacos.plugin.datasource.impl.derby.ConfigInfoAggrMapperByDerby  
com.alibaba.nacos.plugin.datasource.impl.derby.ConfigInfoBetaMapperByDerby  
com.alibaba.nacos.plugin.datasource.impl.derby.ConfigInfoMapperByDerby  
com.alibaba.nacos.plugin.datasource.impl.derby.ConfigInfoTagMapperByDerby  
com.alibaba.nacos.plugin.datasource.impl.derby.ConfigInfoTagsRelationMapperByDerby  
com.alibaba.nacos.plugin.datasource.impl.derby.HistoryConfigInfoMapperByDerby  
com.alibaba.nacos.plugin.datasource.impl.derby.TenantInfoMapperByDerby  
com.alibaba.nacos.plugin.datasource.impl.derby.TenantCapacityMapperByDerby  
com.alibaba.nacos.plugin.datasource.impl.derby.GroupCapacityMapperByDerby  
  
com.alibaba.nacos.plugin.datasource.impl.kingbase8.ConfigInfoAggrMapperByKingbase  
com.alibaba.nacos.plugin.datasource.impl.kingbase8.ConfigInfoBetaMapperByKingbase  
com.alibaba.nacos.plugin.datasource.impl.kingbase8.ConfigInfoMapperByKingbase  
com.alibaba.nacos.plugin.datasource.impl.kingbase8.ConfigInfoTagMapperByKingbase  
com.alibaba.nacos.plugin.datasource.impl.kingbase8.ConfigTagsRelationMapperByKingbase  
com.alibaba.nacos.plugin.datasource.impl.kingbase8.GroupCapacityMapperByKingbase  
com.alibaba.nacos.plugin.datasource.impl.kingbase8.HistoryConfigInfoMapperByKingbase  
com.alibaba.nacos.plugin.datasource.impl.kingbase8.TenantCapacityMapperByKingbase  
com.alibaba.nacos.plugin.datasource.impl.kingbase8.TenantInfoMapperByKingbase

9.异常问题处理

1.除默认public之外自定义的空间及配置删除、编辑异常

处理:
重新在kingbase中执行上述创建约束语句。

2.public空间 修改/删除异常

原因:config_info表中 tenant_id 默认值为NULL
处理:data/kingbase.conf 文件中增加一下 ora_input_emptystr_isnull = off

10.CentOS适配

修改生成出的/bin/shutdown.sh 和/bin/startup.sh
将文件类型改为NUIX。

常用命令

编译

mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U

启动

startup.cmd -m standalone
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要将Docker与Nacos适配达梦数据库,我们可以采取以下步骤: 1. 在Docker中下载并安装Nacos镜像。可以使用Docker Hub上的官方Nacos镜像,该镜像提供了可用于适配不同数据库配置选项。 2. 配置Nacos连接达梦数据库。编辑Nacos配置文件nacos/conf/application.properties,在该文件中找到数据库相关配置项,如`spring.datasource.url`、`spring.datasource.username`、`spring.datasource.password`等,将其按照达梦数据库连接信息进行相应修改。 3. 构建并启动Nacos容器。使用Docker命令行工具,执行类似以下命令来构建并启动Nacos容器: ``` docker run -d -p 8848:8848 --name nacos-server \ -e MODE=standalone \ -e MYSQL_SERVICE_HOST=<数据库主机地址> \ -e MYSQL_SERVICE_PORT=<数据库端口> \ -e MYSQL_SERVICE_DB_NAME=<数据库名称> \ -e MYSQL_SERVICE_USER=<数据库用户名> \ -e MYSQL_SERVICE_PASSWORD=<数据库密码> \ --restart=always \ nacos/nacos-server:latest ``` 替换<数据库主机地址>、<数据库端口>、<数据库名称>、<数据库用户名>、<数据库密码>为实际达梦数据库的信息。 4. 确认Nacos容器已成功启动。使用Docker命令行工具执行以下命令来查看容器状态: ``` docker ps ``` 如果容器状态为Up,则表示Nacos容器已成功运行。 5. 启动达梦数据库。确保达梦数据库已成功启动,并且Nacos容器可以连接到达梦数据库。可以使用数据库客户端验证连接信息是否正确。 6. 访问Nacos管理界面。在浏览器中输入Nacos容器所在主机的IP地址和端口号(默认为8848),访问Nacos的管理界面。在界面中可以配置和管理Nacos的服务、配置等。 通过以上步骤,我们可以在Docker中适配Nacos和达梦数据库实现服务注册和配置管理。这样,我们就可以使用Docker来构建和管理基于Nacos和达梦数据库的应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值