Commit 183a7af6 authored by wangpeng's avatar wangpeng

优化

parent 5bed445f
#flink-operator-repo
# helm repo add flink-operator-repo https://downloads.apache.org/flink/flink-kubernetes-operator-1.9.0/
# helm repo add stable http://mirror.azure.cn/kubernetes/charts
# helm repo add bitnami https://charts.bitnami.com/bitnami
# helm repo add aliyun https://kubernetes.oss-cn-hangzhou.aliyuncs.com/charts
# local:///opt/flink/lib/dinky-app-1.16-1.1.0-jar-with-dependencies.jar
#helm repo add flink-operator-repo https://downloads.apache.org/flink/flink-kubernetes-operator-1.9.0/
#helm repo add stable http://mirror.azure.cn/kubernetes/charts
#helm repo add bitnami https://charts.bitnami.com/bitnami
#helm repo add aliyun https://kubernetes.oss-cn-hangzhou.aliyuncs.com/charts
#local:///opt/flink/lib/dinky-app-1.16-1.1.0-jar-with-dependencies.jar
apiVersion: v1
kind: PersistentVolume
......@@ -161,6 +161,45 @@ spec:
---
apiVersion: v1
kind: PersistentVolume
metadata:
name: nfs-flink-lib-dinky
namespace: flink
labels:
pv: nfs-client-provisioner-lib-dinky
spec:
capacity:
storage: 1Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Recycle
storageClassName: managed-nfs-storage
nfs:
path: /data/flink/dinky
server: 172.27.84.85
---
# 创建PVC
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: nfs-flink-lib-dinky
namespace: flink
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
storageClassName: managed-nfs-storage
selector:
matchLabels:
pv: nfs-client-provisioner-lib-dinky
---
# Flink Session集群
apiVersion: flink.apache.org/v1beta1
kind: FlinkDeployment
......@@ -171,7 +210,7 @@ spec:
image: registry.cn-huhehaote.aliyuncs.com/wangpeng_4/dinky-flink:1.0.0-1.16.3
flinkVersion: v1_16
imagePullPolicy: IfNotPresent # 镜像拉取策略,本地没有则从仓库拉取
ingress: # ingress配置,用于访问flink web页面 测试
ingress: # ingress配置,用于访问flink web页面
template: "flink.k8s.io/{{namespace}}/{{name}}(/|$)(.*)"
className: "nginx"
annotations:
......@@ -209,6 +248,8 @@ spec:
mountPath: /opt/flink/jar
- name: flink-recovery # 挂载log
mountPath: /opt/flink/flink_recovery
- name: flink-lib-dinky # 挂载log
mountPath: /opt/flink/lib/dinky
volumes:
- name: flink-log
persistentVolumeClaim:
......@@ -221,4 +262,7 @@ spec:
claimName: nfs-flink-jar
- name: flink-recovery
persistentVolumeClaim:
claimName: nfs-flink-recovery
\ No newline at end of file
claimName: nfs-flink-recovery
- name: flink-lib-dinky
persistentVolumeClaim:
claimName: nfs-flink-lib-dinky
\ No newline at end of file
......@@ -17,7 +17,7 @@
spring:
datasource:
url: jdbc:mysql://${MYSQL_ADDR:127.0.0.1:3306}/${MYSQL_DATABASE:dinky}?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
username: ${MYSQL_USERNAME:dinky}
password: ${MYSQL_PASSWORD:dinky}
url: jdbc:mysql://${MYSQL_ADDR:172.16.63.106:3306}/${MYSQL_DATABASE:dlink0911}?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
username: ${MYSQL_USERNAME:root}
password: ${MYSQL_PASSWORD:Jkwl@2021}
driver-class-name: com.mysql.cj.jdbc.Driver
......@@ -16,7 +16,7 @@ spring:
# If you use pgsql database, please configure pgsql database connection information in application-pgsql.yml
# If you use the h2 database, please configure the h2 database connection information in application-h2.yml,
# note: the h2 database is only for experience use, and the related data that has been created cannot be migrated, please use it with caution
active: ${DB_ACTIVE:h2} #[h2,mysql,pgsql]
active: mysql #[h2,mysql,pgsql]
include:
- jmx
- flyway
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.cdc;
import org.dinky.assertion.Asserts;
import org.dinky.cdc.utils.FlinkStatementUtil;
import org.dinky.data.model.Column;
import org.dinky.data.model.FlinkCDCConfig;
import org.dinky.data.model.Schema;
import org.dinky.data.model.Table;
import org.dinky.executor.CustomTableEnvironment;
import org.dinky.utils.JsonUtils;
import com.google.common.collect.Lists;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
......@@ -42,47 +15,30 @@ import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.operations.ModifyOperation;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.types.logical.BigIntType;
import org.apache.flink.table.types.logical.BooleanType;
import org.apache.flink.table.types.logical.DateType;
import org.apache.flink.table.types.logical.DecimalType;
import org.apache.flink.table.types.logical.DoubleType;
import org.apache.flink.table.types.logical.FloatType;
import org.apache.flink.table.types.logical.IntType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.SmallIntType;
import org.apache.flink.table.types.logical.TimeType;
import org.apache.flink.table.types.logical.TimestampType;
import org.apache.flink.table.types.logical.TinyIntType;
import org.apache.flink.table.types.logical.VarBinaryType;
import org.apache.flink.table.types.logical.VarCharType;
import org.apache.flink.table.types.logical.*;
import org.apache.flink.types.RowKind;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
import org.dinky.assertion.Asserts;
import org.dinky.cdc.utils.FlinkStatementUtil;
import org.dinky.data.model.Column;
import org.dinky.data.model.FlinkCDCConfig;
import org.dinky.data.model.Schema;
import org.dinky.data.model.Table;
import org.dinky.executor.CustomTableEnvironment;
import org.dinky.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.bind.DatatypeConverter;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.xml.bind.DatatypeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
public abstract class AbstractSinkBuilder implements SinkBuilder {
protected ObjectMapper objectMapper = new ObjectMapper();
......@@ -240,7 +196,8 @@ public abstract class AbstractSinkBuilder implements SinkBuilder {
DataStream<RowData> rowDataDataStream,
Table table,
List<String> columnNameList,
List<LogicalType> columnTypeList) {}
List<LogicalType> columnTypeList) {
}
protected List<Operation> createInsertOperations(
CustomTableEnvironment customTableEnvironment, Table table, String viewName, String tableName) {
......@@ -516,9 +473,6 @@ public abstract class AbstractSinkBuilder implements SinkBuilder {
}
}
tableName = sink.getOrDefault(FlinkCDCConfig.TABLE_PREFIX, "")
+ tableName
+ sink.getOrDefault(FlinkCDCConfig.TABLE_SUFFIX, "");
// table.lower and table.upper can not be true at the same time
if (Boolean.parseBoolean(sink.get(FlinkCDCConfig.TABLE_LOWER))
&& Boolean.parseBoolean(sink.get(FlinkCDCConfig.TABLE_UPPER))) {
......@@ -544,9 +498,12 @@ public abstract class AbstractSinkBuilder implements SinkBuilder {
// add schema
if (Boolean.parseBoolean(sink.get("table.prefix.schema"))) {
tableName = table.getSchema() + "_" + tableName;
logger.info("Add schema to table name: {}", tableName);
tableName = table.getSchema() + "." + tableName;
}
tableName = sink.getOrDefault(FlinkCDCConfig.TABLE_PREFIX, "")
+ tableName
+ sink.getOrDefault(FlinkCDCConfig.TABLE_SUFFIX, "");
return tableName;
}
......@@ -587,4 +544,4 @@ public abstract class AbstractSinkBuilder implements SinkBuilder {
protected ZoneId getSinkTimeZone() {
return this.sinkTimeZone;
}
}
}
\ No newline at end of file
......@@ -24,6 +24,7 @@ import org.dinky.cdc.debezium.DebeziumCustomConverter;
import org.apache.flink.cdc.connectors.shaded.org.apache.kafka.connect.data.SchemaBuilder;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import io.debezium.spi.converter.RelationalColumn;
......@@ -76,11 +77,13 @@ public class MysqlDebeziumConverter extends DebeziumCustomConverter {
break;
case "DATETIME":
case "TIMESTAMP":
schemaBuilder = SchemaBuilder.int64().optional().name("com.darcytech.debezium.datetime.long");
converterRegistration.register(schemaBuilder, value -> {
if (value == null) {
return null;
} else if (value instanceof java.time.LocalDateTime) {
return datetimeFormatter.format((java.time.LocalDateTime) value);
LocalDateTime localDateTime = (LocalDateTime) value;
return localDateTime.atZone(zoneId).toInstant().toEpochMilli();
} else if (value instanceof java.time.ZonedDateTime) {
return datetimeFormatter.format(((java.time.ZonedDateTime) value)
.withZoneSameInstant(zoneId)
......
......@@ -25,6 +25,12 @@ import org.apache.flink.cdc.connectors.shaded.org.apache.kafka.connect.data.Sche
import io.debezium.spi.converter.RelationalColumn;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
/**
* @author <a href="mailto:kindbgen@gmail.com">Kindbgen<a/>
* @description PostgreSQL 转换器
......@@ -70,13 +76,21 @@ public class PostgresDebeziumConverter extends DebeziumCustomConverter {
});
break;
case "TIMESTAMP":
schemaBuilder = SchemaBuilder.int64().optional().name("com.darcytech.debezium.datetime.long");
converterRegistration.register(schemaBuilder, value -> {
if (value == null) {
return null;
} else if (value instanceof java.sql.Timestamp) {
return datetimeFormatter.format(((java.sql.Timestamp) value).toLocalDateTime());
return ((java.sql.Timestamp) value).toLocalDateTime().atZone(zoneId).toInstant().toEpochMilli();
// return datetimeFormatter.format(((java.sql.Timestamp) value).toLocalDateTime());
} else if (value instanceof java.time.LocalDateTime) {
return datetimeFormatter.format((java.time.LocalDateTime) value);
LocalDateTime localDateTime = (LocalDateTime) value;
return localDateTime.atZone(zoneId).toInstant().toEpochMilli();
} else if (value instanceof ZonedDateTime) {
ZonedDateTime zonedDateTime = (ZonedDateTime) value;
return zonedDateTime.withZoneSameInstant(zoneId).toInstant().toEpochMilli();
} else if (value instanceof java.time.Instant) {
return ((java.time.Instant) value).plus(-8, java.time.temporal.ChronoUnit.HOURS).toEpochMilli();
} else {
return this.failConvert(value, schemaName);
}
......@@ -87,4 +101,9 @@ public class PostgresDebeziumConverter extends DebeziumCustomConverter {
break;
}
}
private static Instant parseInstant(String instantString) {
DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
return Instant.from(formatter.parse(instantString));
}
}
......@@ -194,6 +194,7 @@ public class KafkaSinkBuilder extends AbstractSinkBuilder implements Serializabl
kafkaSinkBuilder.setTransactionalIdPrefix(
kafkaProducerConfig.getProperty("transactional.id") + "-" + topic);
}
KafkaSink<String> kafkaSink = kafkaSinkBuilder.build();
process.getSideOutput(v).rebalance().sinkTo(kafkaSink).name(topic);
});
......
......@@ -19,17 +19,18 @@
package org.dinky.cdc.postgres;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cdc.connectors.base.options.StartupOptions;
import org.apache.flink.cdc.connectors.postgres.source.PostgresSourceBuilder;
import org.apache.flink.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.dinky.assertion.Asserts;
import org.dinky.cdc.AbstractCDCBuilder;
import org.dinky.cdc.CDCBuilder;
import org.dinky.constant.FlinkParamConstant;
import org.dinky.data.model.FlinkCDCConfig;
import org.apache.flink.cdc.connectors.postgres.PostgreSQLSource;
import org.apache.flink.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import java.util.List;
import java.util.Map;
import java.util.Properties;
......@@ -57,7 +58,6 @@ public class PostgresCDCBuilder extends AbstractCDCBuilder implements CDCBuilder
@Override
public DataStreamSource<String> build(StreamExecutionEnvironment env) {
String decodingPluginName = config.getSource().get("decoding.plugin.name");
String slotName = config.getSource().get("slot.name");
......@@ -67,14 +67,12 @@ public class PostgresCDCBuilder extends AbstractCDCBuilder implements CDCBuilder
debeziumProperties.setProperty(entry.getKey(), entry.getValue());
}
}
PostgreSQLSource.Builder<String> sourceBuilder = PostgreSQLSource.<String>builder()
PostgresSourceBuilder<String> sourceBuilder = PostgresSourceBuilder.PostgresIncrementalSource.<String>builder()
.hostname(config.getHostname())
.port(config.getPort())
.database(config.getDatabase())
.username(config.getUsername())
.password(config.getPassword());
if (Asserts.isNotNullString(config.getSchema())) {
String[] schemas = config.getSchema().split(FlinkParamConstant.SPLIT);
sourceBuilder.schemaList(schemas);
......@@ -99,8 +97,21 @@ public class PostgresCDCBuilder extends AbstractCDCBuilder implements CDCBuilder
if (Asserts.isNotNullString(slotName)) {
sourceBuilder.slotName(slotName);
}
return env.addSource(sourceBuilder.build(), "Postgres CDC Source");
if (Asserts.isNotNullString(config.getStartupMode())) {
switch (config.getStartupMode().toLowerCase()) {
case "initial":
sourceBuilder.startupOptions(StartupOptions.initial());
break;
case "latest-offset":
sourceBuilder.startupOptions(StartupOptions.latest());
break;
default:
}
} else {
sourceBuilder.startupOptions(StartupOptions.latest());
}
// return env.addSource(sourceBuilder.build(), "Postgres CDC Source");
return env.fromSource(sourceBuilder.build(), WatermarkStrategy.noWatermarks(), "Postgres CDC Source");
}
@Override
......
......@@ -115,6 +115,10 @@
<groupId>org.apache.flink</groupId>
<artifactId>flink-shaded-guava</artifactId>
</exclusion>
<exclusion>
<groupId>io.debezium</groupId>
<artifactId>debezium-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
......
......@@ -814,74 +814,6 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<version>${spotless.version}</version>
<configuration>
<ratchetFrom>${spotless.ratchetFrom}</ratchetFrom>
<java>
<palantirJavaFormat>
<!-- Optionally specify a version -->
<version>2.34.0</version>
</palantirJavaFormat>
<removeUnusedImports />
<importOrder>
<order>\#,org.dinky,org.apache,java,javassist,javax,org,com,</order>
</importOrder>
<licenseHeader>
<file>style/license_header</file>
</licenseHeader>
<replaceRegex>
<name>Remove wildcard imports</name>
<searchRegex>import\s+[^\*\s]+\*;(\r\n|\r|\n)</searchRegex>
<replacement>$1</replacement>
</replaceRegex>
</java>
<pom>
<sortPom>
<encoding>UTF-8</encoding>
<nrOfIndentSpace>4</nrOfIndentSpace>
<keepBlankLines>true</keepBlankLines>
<indentBlankLines>false</indentBlankLines>
<indentSchemaLocation>true</indentSchemaLocation>
<spaceBeforeCloseEmptyElement>true</spaceBeforeCloseEmptyElement>
<sortModules>false</sortModules>
<sortExecutions>false</sortExecutions>
<predefinedSortOrder>custom_1</predefinedSortOrder>
<expandEmptyElements>false</expandEmptyElements>
<sortProperties>true</sortProperties>
</sortPom>
<replace>
<name>Leading blank line</name>
<search>project</search>
<replacement>project</replacement>
</replace>
</pom>
<typescript>
<includes>
<!-- You have to set the target manually -->
<include>dinky-web/src/**/*.ts</include>
<include>dinky-web/src/**/*.tsx</include>
<include>dinky-web/src/**/*.js</include>
</includes>
<licenseHeader>
<file>style/license_header</file>
<delimiter>(?!(\/\*|\ \*|\/\*|\/\/|\s))</delimiter>
</licenseHeader>
</typescript>
</configuration>
<executions>
<execution>
<id>spotless-check</id>
<goals>
<goal>check</goal>
</goals>
<phase>validate</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment