Skip to content

Commit

Permalink
[feat-#1062][redis] Add source connector and reader connector of redis.
Browse files Browse the repository at this point in the history
  • Loading branch information
qingxing authored and FlechazoW committed Jul 29, 2022
1 parent 0bd868c commit 8e2db7d
Show file tree
Hide file tree
Showing 15 changed files with 612 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisCommands;
import redis.clients.jedis.JedisPool;
Expand Down Expand Up @@ -204,10 +205,8 @@ public void closeJedis(JedisCommands jedis) {

public void close(JedisCommands jedis) {
try {
if (jedis != null) {
if (jedis instanceof Closeable) {
((Closeable) jedis).close();
}
if (jedis != null && ((Jedis) jedis).isConnected()) {
((Closeable) jedis).close();
}
if (jedisSentinelPool != null) {
jedisSentinelPool.close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,14 @@ public RedisColumnConverter(RedisConf redisConf) {

@Override
public RowData toInternal(Object input) {
return null;
Map<String, String> map = (Map<String, String>) input;
List<FieldConf> column = redisConf.getColumn();
ColumnRowData rowData = new ColumnRowData(column.size());
for (int i = 0; i < column.size(); i++) {
StringColumn value = new StringColumn(map.get(column.get(i).getName()));
rowData.addField(value);
}
return rowData;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* 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 com.dtstack.chunjun.connector.redis.converter;

import com.dtstack.chunjun.throwable.UnsupportedTypeException;

import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.types.DataType;

import java.util.Locale;

/** @Author OT @Date 2022/7/27 */
public class RedisRawTypeConverter {
public static DataType apply(String type) {
switch (type.toUpperCase(Locale.ENGLISH)) {
case "STRING":
return DataTypes.STRING();
default:
throw new UnsupportedTypeException(type);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* 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 com.dtstack.chunjun.connector.redis.inputsplit;

import org.apache.flink.core.io.GenericInputSplit;

import java.util.List;

/** @Author OT @Date 2022/7/27 */
public class RedisInputSplit extends GenericInputSplit {
private List<String> key;

public RedisInputSplit(int partitionNumber, int totalNumberOfPartitions, List<String> key) {
super(partitionNumber, totalNumberOfPartitions);
this.key = key;
}

public List<String> getKey() {
return key;
}

public void setKey(List<String> key) {
this.key = key;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

import com.dtstack.chunjun.connector.redis.conf.RedisConf;
import com.dtstack.chunjun.connector.redis.connection.RedisSyncClient;
import com.dtstack.chunjun.connector.redis.enums.RedisConnectType;
import com.dtstack.chunjun.connector.redis.util.RedisUtil;
import com.dtstack.chunjun.converter.AbstractRowConverter;
import com.dtstack.chunjun.lookup.AbstractAllTableFunction;
import com.dtstack.chunjun.lookup.conf.LookupConf;
Expand All @@ -31,17 +31,13 @@
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisCommands;
import redis.clients.jedis.JedisPool;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
Expand Down Expand Up @@ -95,7 +91,8 @@ protected void loadData(Object cacheRef) {
}

Set<String> keys =
getRedisKeys(redisConf.getRedisConnectType(), jedis, keyPattern.toString());
RedisUtil.getRedisKeys(
redisConf.getRedisConnectType(), jedis, keyPattern.toString());
if (CollectionUtils.isEmpty(keys)) {
return;
}
Expand All @@ -122,22 +119,4 @@ protected void loadData(Object cacheRef) {
redisSyncClient.closeJedis(jedis);
}
}

private Set<String> getRedisKeys(
RedisConnectType redisType, JedisCommands jedis, String keyPattern) {
if (!redisType.equals(RedisConnectType.CLUSTER)) {
return ((Jedis) jedis).keys(keyPattern);
}
Set<String> keys = new TreeSet<>();
Map<String, JedisPool> clusterNodes = ((JedisCluster) jedis).getClusterNodes();
for (String k : clusterNodes.keySet()) {
JedisPool jp = clusterNodes.get(k);
try (Jedis connection = jp.getResource()) {
keys.addAll(connection.keys(keyPattern));
} catch (Exception e) {
LOG.error("Getting keys error", e);
}
}
return keys;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,7 @@ public class RedisOptions {

public static final ConfigOption<String> REDIS_DATA_MODE =
ConfigOptions.key("mode").stringType().noDefaultValue().withDescription("mode");

public static final ConfigOption<String> KEY_PREFIX =
ConfigOptions.key("keyPrefix").stringType().noDefaultValue().withDescription("mode");
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,20 @@
import com.dtstack.chunjun.connector.redis.lookup.RedisLruTableFunction;
import com.dtstack.chunjun.enums.CacheType;
import com.dtstack.chunjun.lookup.conf.LookupConf;
import com.dtstack.chunjun.source.DtInputFormatSourceFunction;
import com.dtstack.chunjun.table.connector.source.ParallelAsyncTableFunctionProvider;
import com.dtstack.chunjun.table.connector.source.ParallelSourceFunctionProvider;
import com.dtstack.chunjun.table.connector.source.ParallelTableFunctionProvider;

import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.connector.ChangelogMode;
import org.apache.flink.table.connector.source.DynamicTableSource;
import org.apache.flink.table.connector.source.LookupTableSource;
import org.apache.flink.table.connector.source.ScanTableSource;
import org.apache.flink.table.connector.source.abilities.SupportsProjectionPushDown;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.utils.TableSchemaUtils;
import org.apache.flink.util.Preconditions;
Expand All @@ -40,7 +47,8 @@
* @create 2021-06-21 19:08
* @description
*/
public class RedisDynamicTableSource implements LookupTableSource, SupportsProjectionPushDown {
public class RedisDynamicTableSource
implements ScanTableSource, LookupTableSource, SupportsProjectionPushDown {

protected TableSchema physicalSchema;
protected final RedisConf redisConf;
Expand Down Expand Up @@ -99,4 +107,20 @@ public boolean supportsNestedProjection() {
public void applyProjection(int[][] projectedFields) {
this.physicalSchema = TableSchemaUtils.projectSchema(physicalSchema, projectedFields);
}

@Override
public ChangelogMode getChangelogMode() {
return ChangelogMode.insertOnly();
}

@Override
public ScanRuntimeProvider getScanRuntimeProvider(ScanContext runtimeProviderContext) {
RedisInputFormatBuilder builder = new RedisInputFormatBuilder();
final RowType rowType = (RowType) physicalSchema.toRowDataType().getLogicalType();
TypeInformation<RowData> typeInformation = InternalTypeInfo.of(rowType);
builder.setRedisConf(redisConf);
builder.setRowConverter(new RedisRowConverter(rowType));
return ParallelSourceFunctionProvider.of(
new DtInputFormatSourceFunction<>(builder.finish(), typeInformation), false, 1);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/*
* 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 com.dtstack.chunjun.connector.redis.source;

import com.dtstack.chunjun.connector.redis.conf.RedisConf;
import com.dtstack.chunjun.connector.redis.connection.RedisSyncClient;
import com.dtstack.chunjun.connector.redis.inputsplit.RedisInputSplit;
import com.dtstack.chunjun.connector.redis.util.RedisUtil;
import com.dtstack.chunjun.source.format.BaseRichInputFormat;
import com.dtstack.chunjun.throwable.ReadRecordException;

import org.apache.flink.core.io.InputSplit;
import org.apache.flink.table.data.RowData;

import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.JedisCommands;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/** @Author OT @Date 2022/7/26 */
public class RedisInputFormat extends BaseRichInputFormat {
private transient RedisSyncClient redisSyncClient;

private transient Iterator<String> keyIterator;
/** redis Conf */
private RedisConf redisConf;
/** jedis */
private JedisCommands jedis;

@Override
protected InputSplit[] createInputSplitsInternal(int minNumSplits) throws Exception {
redisSyncClient = new RedisSyncClient(redisConf);
jedis = redisSyncClient.getJedis();
Set<String> keys = new HashSet();
if (StringUtils.isNotBlank(redisConf.getKeyPrefix())) {
keys.addAll(
RedisUtil.getRedisKeys(
redisConf.getRedisConnectType(), jedis, redisConf.getKeyPrefix()));
}
Iterator<String> iterator = keys.iterator();
RedisInputSplit[] inputSplits = new RedisInputSplit[minNumSplits];
if (keys.size() == 0) {
throw new RuntimeException("There is no" + redisConf.getKeyPrefix() + "with key");
}
int keySplitCount = keys.size() / minNumSplits;
for (int i = 0; i < inputSplits.length; i++) {
List<String> list = new LinkedList();
for (int j = 0; j < keySplitCount && iterator.hasNext(); j++) {
list.add(iterator.next());
}
inputSplits[i] = new RedisInputSplit(i, minNumSplits, list);
}
while (iterator.hasNext()) {
inputSplits[minNumSplits - 1].getKey().add(iterator.next());
}
redisSyncClient.close(jedis);
return inputSplits;
}

@Override
protected void openInternal(InputSplit inputSplit) throws IOException {
RedisInputSplit redisInputSplit = (RedisInputSplit) inputSplit;
redisSyncClient = new RedisSyncClient(redisConf);
jedis = redisSyncClient.getJedis();
keyIterator = redisInputSplit.getKey().iterator();
}

@Override
protected RowData nextRecordInternal(RowData rowData) throws ReadRecordException {
if (!keyIterator.hasNext()) {
return null;
}
Map<String, String> map = jedis.hgetAll(keyIterator.next());
try {
RowData row = rowConverter.toInternal(map);
return row;
} catch (Exception e) {
throw new ReadRecordException("", e, 0, rowData);
}
}

@Override
protected void closeInternal() throws IOException {
redisSyncClient.close(jedis);
}

@Override
public boolean reachedEnd() throws IOException {
return !keyIterator.hasNext();
}

public RedisConf getRedisConf() {
return redisConf;
}

public void setRedisConf(RedisConf redisConf) {
this.redisConf = redisConf;
}
}
Loading

0 comments on commit 8e2db7d

Please sign in to comment.