前言

因公司要求数据库需要使用阿里的oceanbase数据库,但是Nacos官方仅支持mysql数据库,特对此进行改造以满足数据库要求,文末提供完整版本的下载及源码地址。

适配工作

一、下载多数据源分支

github地址,选择feature_multiple_datasource_support分支并clone至本地。
在这里插入图片描述

二. jar包引入及更换

由于此分支支持oracle12c,需要更换驱动包版本

1. nacos-all 下pom文件修改

<properties>
		...
        <!--    移除ojdbc8依赖版本    -->
        <!--        <ojdbc.version>19.3.0.0</ojdbc.version>-->
        <!--     更改oracle版本为ojdbc6   -->
        <ojdbc.version>11.2.0.3</ojdbc.version>
        <!--    增加对obdriver依赖支持    -->
        <obdriver.version>1.0.0</obdriver.version>
        ...
</properties>

<!-- 管理依赖版本号,子项目不会默认依赖 -->
<dependencyManagement>
    <dependencies>
    ...
         <!-- oracle包 -->
         <dependency>
             <groupId>com.oracle</groupId>
             <artifactId>ojdbc6</artifactId>
             <version>${ojdbc.version}</version>
         </dependency>
         <!--    oceanbase数据库支持        -->
         <dependency>
             <groupId>com.alipay</groupId>
             <artifactId>obdriver</artifactId>
             <version>1.0.0</version>
         </dependency>
	...
<!--移除ojdbc8依赖版本-->
<!--            <dependency>-->
<!--                <groupId>com.oracle.ojdbc</groupId>-->
<!--                <artifactId>ojdbc8</artifactId>-->
<!--                <version>${ojdbc.version}</version>-->
<!--            </dependency>-->
...
    </dependencies>
</dependencyManagement>

2. nacos-config的pom文件增加引入需要支持的数据库驱动,并取消oracle高版本驱动引入

<!--        <dependency>-->
<!--            <groupId>com.oracle.ojdbc</groupId>-->
<!--            <artifactId>ojdbc8</artifactId>-->
<!--        </dependency>-->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alipay</groupId>
            <artifactId>obdriver</artifactId>
        </dependency>

三、修改oceanbase不支持对clob字段使用DISTINCT【ORACLE用户可跳过此步骤】

1. nacos-config下

com.alibaba.nacos.config.server.modules.repository.ConfigInfoAggrRepository,去除DISTINCT关键字


    /**
     * findAllAggrGroup.
     *
     * @return
     */
    @Query(value = "SELECT  data_id,group_id,tenant_id,id,app_name,content,gmt_modified,datum_id FROM config_info_aggr", nativeQuery = true)
    List<ConfigInfoAggrEntity> findAllAggrGroup();

com.alibaba.nacos.config.server.service.repository.extrnal.ExternalStoragePersistServiceImp

    @Override
    public List<ConfigInfoChanged> findAllAggrGroup() {
        List<ConfigInfoAggrEntity> list = configInfoAggrRepository.findAllAggrGroup();
        // OB不支持clob去重
        //java8 去重 data_id,group_id,tenant_id,id,app_name,content,gmt_modified,datum_id
        List<ConfigInfoAggrEntity> distinctList = list.stream()
            .collect(Collectors.collectingAndThen(Collectors.toCollection(
                () -> new TreeSet<>(Comparator.comparing(o -> o.getDataId()+o.getGroupId()+o.getTenantId()+o.getId()+o.getAppName()+o.getContent()+o.getGmtModified()+o.getDatumId()))),ArrayList::new ));
        return ConfigInfoChangedMapStruct.INSTANCE.convertConfigInfoChangedList(distinctList);
    }

四、对数据库映射实体的主键逻辑修改【需要配合后续的序列语句使用】

因为mysql使用的是自增序列,oracle11g并不支持,所以在使用jpa时需要指定主键及使用的索引的名字,需要对实体类进行修改

1. nacos-config下

com.alibaba.nacos.config.server.modules.entity

在这里插入图片描述
这里只举一个示例,蓝色部分都是有修改的,详细代码可在文末代码中获取。

@Data
@Entity
@Table(name = CONFIG_INFO_TABLE_NAME)
public class ConfigInfoEntity implements Serializable {

    /**
     * jpa id
     */
    @Id
    @Column(name = "id")
    @SequenceGenerator(
        name = "SEQ_CONFIG_INFO",
        sequenceName = "SEQ_CONFIG_INFO",
        allocationSize = 1)
    @GeneratedValue(
        strategy = GenerationType.SEQUENCE,
        generator = "SEQ_CONFIG_INFO"
    )
    private long id;

    @Column(name = "data_id")
    private String dataId;

    @Column(name = "group_id")
    private String groupId;

    @Column(name = "content")

需要注意的是PermissionsEntity类的resource字段,在建表语句中变成了resources,需要在对应字段修改下


    /**
     * resource.
     */
    @Column(name = "resources")
    private String resource;

五、修改nacos-console配置文件application.properties



#*************** Spring Boot Related Configurations ***************#
### Default web context path:
server.servlet.contextPath=/nacos
### Default web server port:
server.port=8848

#*************** Network Related Configurations ***************#
### If prefer hostname over ip for Nacos server addresses in cluster.conf:
# nacos.inetutils.prefer-hostname-over-ip=false

### Specify local server's IP:
# nacos.inetutils.ip-address=


#*************** Config Module Related Configurations ***************#
### If use MySQL as datasource:
# spring.datasource.platform=mysql

### Count of DB:
# db.num=1

### Connect URL of DB:
# db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
# db.user.0=nacos
# db.password.0=nacos


#*************** Naming Module Related Configurations ***************#
### Data dispatch task execution period in milliseconds:
# nacos.naming.distro.taskDispatchPeriod=200

### Data count of batch sync task:
# nacos.naming.distro.batchSyncKeyCount=1000

### Retry delay in milliseconds if sync task failed:
# nacos.naming.distro.syncRetryDelay=5000

### If enable data warmup. If set to false, the server would accept request without local data preparation:
# nacos.naming.data.warmup=true

### If enable the instance auto expiration, kind like of health check of instance:
# nacos.naming.expireInstance=true

nacos.naming.empty-service.auto-clean=true
nacos.naming.empty-service.clean.initial-delay-ms=50000
nacos.naming.empty-service.clean.period-time-ms=30000


#*************** CMDB Module Related Configurations ***************#
### The interval to dump external CMDB in seconds:
# nacos.cmdb.dumpTaskInterval=3600

### The interval of polling data change event in seconds:
# nacos.cmdb.eventTaskInterval=10

### The interval of loading labels in seconds:
# nacos.cmdb.labelTaskInterval=300

### If turn on data loading task:
# nacos.cmdb.loadDataAtStart=false


#*************** Metrics Related Configurations ***************#
### Metrics for prometheus
#management.endpoints.web.exposure.include=*

### Metrics for elastic search
management.metrics.export.elastic.enabled=false
#management.metrics.export.elastic.host=http://localhost:9200

### Metrics for influx
management.metrics.export.influx.enabled=false
#management.metrics.export.influx.db=springboot
#management.metrics.export.influx.uri=http://localhost:8086
#management.metrics.export.influx.auto-create-db=true
#management.metrics.export.influx.consistency=one
#management.metrics.export.influx.compressed=true


#*************** Access Log Related Configurations ***************#
### If turn on the access log:
server.tomcat.accesslog.enabled=true

### The access log pattern:
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{User-Agent}i %{Request-Source}i

### The directory of access log:
server.tomcat.basedir=


#*************** Access Control Related Configurations ***************#
### If enable spring security, this option is deprecated in 1.2.0:
#spring.security.enabled=false

### The ignore urls of auth, is deprecated in 1.2.0:
nacos.security.ignore.urls=/,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-ui/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/**

### The auth system to use, currently only 'nacos' is supported:
nacos.core.auth.system.type=nacos

### If turn on auth system:
nacos.core.auth.enabled=false

### The token expiration in seconds:
nacos.core.auth.default.token.expire.seconds=18000

### The default token:
nacos.core.auth.default.token.secret.key=SecretKey012345678901234567890123456789012345678901234567890123456789

### Turn on/off caching of auth information. By turning on this switch, the update of auth information would have a 15 seconds delay.
nacos.core.auth.caching.enabled=true

### Since 1.4.1, Turn on/off white auth for user-agent: nacos-server, only for upgrade from old version.
nacos.core.auth.enable.userAgentAuthWhite=false

### Since 1.4.1, worked when nacos.core.auth.enabled=true and nacos.core.auth.enable.userAgentAuthWhite=false.
### The two properties is the white list for auth and used by identity the request from other server.
nacos.core.auth.server.identity.key=serverIdentity
nacos.core.auth.server.identity.value=security

#*************** Istio Related Configurations ***************#
### If turn on the MCP server:
nacos.istio.mcp.server.enabled=false



###*************** Add from 1.3.0 ***************###


#*************** Core Related Configurations ***************#

### set the WorkerID manually
# nacos.core.snowflake.worker-id=

### Member-MetaData
# nacos.core.member.meta.site=
# nacos.core.member.meta.adweight=
# nacos.core.member.meta.weight=

### MemberLookup
### Addressing pattern category, If set, the priority is highest
# nacos.core.member.lookup.type=[file,address-server]
## Set the cluster list with a configuration file or command-line argument
# nacos.member.list=192.168.16.101:8847?raft_port=8807,192.168.16.101?raft_port=8808,192.168.16.101:8849?raft_port=8809
## for AddressServerMemberLookup
# Maximum number of retries to query the address server upon initialization
# nacos.core.address-server.retry=5
## Server domain name address of [address-server] mode
# address.server.domain=jmenv.tbsite.net
## Server port of [address-server] mode
# address.server.port=8080
## Request address of [address-server] mode
# address.server.url=/nacos/serverlist

#*************** JRaft Related Configurations ***************#

### Sets the Raft cluster election timeout, default value is 5 second
# nacos.core.protocol.raft.data.election_timeout_ms=5000
### Sets the amount of time the Raft snapshot will execute periodically, default is 30 minute
# nacos.core.protocol.raft.data.snapshot_interval_secs=30
### raft internal worker threads
# nacos.core.protocol.raft.data.core_thread_num=8
### Number of threads required for raft business request processing
# nacos.core.protocol.raft.data.cli_service_thread_num=4
### raft linear read strategy. Safe linear reads are used by default, that is, the Leader tenure is confirmed by heartbeat
# nacos.core.protocol.raft.data.read_index_type=ReadOnlySafe
### rpc request timeout, default 5 seconds
# nacos.core.protocol.raft.data.rpc_request_timeout_ms=5000



#nacos.datasource.type=MYSQL
#
#nacos.datasource.relational.dsList[0].url=jdbc:mysql://localhost:3306/nacos-devtest?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
#nacos.datasource.relational.dsList[0].username=root
#nacos.datasource.relational.dsList[0].password=root
#nacos.datasource.relational.dsList[0].driver-class-name=com.mysql.jdbc.Driver
#nacos.datasource.relational.dsList[0].hikari.connection-timeout=10000
#nacos.datasource.relational.dsList[0].hikari.idle-timeout=120000
#nacos.datasource.relational.dsList[0].hikari.max-lifetime=240000
#nacos.datasource.relational.dsList[0].hikari.maximum-pool-size=20
#nacos.datasource.relational.dsList[0].hikari.data-source-properties.cachePrepStmts=true
#nacos.datasource.relational.dsList[0].hikari.data-source-properties.prepStmtCacheSize=250
#nacos.datasource.relational.dsList[0].hikari.data-source-properties.prepStmtCacheSqlLimit=2048
#nacos.datasource.relational.dsList[0].hikari.connection-test-query=SELECT 1 FROM dual
#
#
#
#nacos.datasource.relational.dsList[1].url=jdbc:mysql://localhost:3306/nacos-devtest?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
#nacos.datasource.relational.dsList[1].username=root
#nacos.datasource.relational.dsList[1].password=root
#nacos.datasource.relational.dsList[1].hikari.connection-test-query=SELECT 1 FROM dual
#nacos.datasource.relational.dsList[1].hikari.connection-timeout=60000
#nacos.datasource.relational.dsList[1].hikari.maximum-pool-size=20
#nacos.datasource.relational.dsList[1]-enable=false
#

## jpa
spring.data.jpa.repositories.enabled=true
spring.jpa.show-sql=true
## The datasource is used by oracle
# spring.jpa.hibernate.naming.physical-strategy=com.alibaba.nacos.config.server.configuration.NacosPhysicalNamingStrategy


# oracle数据库配置
#nacos.datasource.type=ORACLE
#
#nacos.datasource.relational.dsList[0].url=jdbc:oracle:thin:@ip/database
#nacos.datasource.relational.dsList[0].username=***
#nacos.datasource.relational.dsList[0].password=***
#nacos.datasource.relational.dsList[0].driver-class-name=oracle.jdbc.driver.OracleDriver
#nacos.datasource.relational.dsList[0].hikari.connection-timeout=10000
#nacos.datasource.relational.dsList[0].hikari.idle-timeout=120000
#nacos.datasource.relational.dsList[0].hikari.max-lifetime=240000
#nacos.datasource.relational.dsList[0].hikari.maximum-pool-size=20
#nacos.datasource.relational.dsList[0].hikari.data-source-properties.cachePrepStmts=true
#nacos.datasource.relational.dsList[0].hikari.data-source-properties.prepStmtCacheSize=250
#nacos.datasource.relational.dsList[0].hikari.data-source-properties.prepStmtCacheSqlLimit=2048
#nacos.datasource.relational.dsList[0].hikari.connection-test-query=SELECT 1 FROM dual

# OB【oracle】数据库配置
nacos.datasource.type=ORACLE
#
nacos.datasource.relational.dsList[0].url=jdbc:oceanbase://ip/database?useUnicode=true&characterEncoding=utf-8
nacos.datasource.relational.dsList[0].username=***
nacos.datasource.relational.dsList[0].password=***
nacos.datasource.relational.dsList[0].driver-class-name=com.alipay.oceanbase.obproxy.mysql.jdbc.Driver
nacos.datasource.relational.dsList[0].hikari.connection-timeout=10000
nacos.datasource.relational.dsList[0].hikari.idle-timeout=120000
nacos.datasource.relational.dsList[0].hikari.max-lifetime=240000
nacos.datasource.relational.dsList[0].hikari.maximum-pool-size=20
nacos.datasource.relational.dsList[0].hikari.data-source-properties.cachePrepStmts=true
nacos.datasource.relational.dsList[0].hikari.data-source-properties.prepStmtCacheSize=250
nacos.datasource.relational.dsList[0].hikari.data-source-properties.prepStmtCacheSqlLimit=2048
nacos.datasource.relational.dsList[0].hikari.connection-test-query=SELECT 1 FROM dual

六、idea启动单机nacos进行调试

nacos-console模块的Nacos启动类

在这里插入图片描述

-Dnacos.standalone=true

在这里插入图片描述
再次启动及单机模式。
在这里插入图片描述
在这里插入图片描述

七、打包发布

在nacos-all目录下允许打包命令

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

如果打包失败,报错如下:

Failed to execute goal org.apache.rat:apache-rat-plugin:0.12:check (default) on project flink-parent: Too many files with unapproved license: 4 See RAT report in: D:\ffffff\flink-release-1.10.0\flink-release-1.10.0\target\rat.txt

打包命令增加 -Drat.skip=true 参数 ,跳过licensing 检查

更改为

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

在distribution\target 目录下会产生工程
在这里插入图片描述

八、资源

修改完成的版本,选择oracle11g分支或者ob分支即可拿到即用版本。数据库sql放置在config下的src\main\resources\META-INF\nacos-oracle-11g.sql文件中。
在这里插入图片描述

Logo

了解最新的技术洞察和前沿趋势,参与 OceanBase 定期举办的线下活动,与行业开发者互动交流

更多推荐