方便更快捷的说明问题,可以按需填写(可删除)
使用环境:Java1.8版本,maven项目,非srping和springboot环境
场景、问题:使用原生的shardingsharsphere-jdbc-core连接数据库报错Exception in thread “main” org.apache.shardingsphere.infra.config.exception.ShardingSphereConfigurationException: Can not load table: FATAL: password authentication failed for user “Leon”
已进行操作:
这是配置文件:
mode:
type: Memory
dataSources:
ds_0:
url: jdbc:postgresql://10.100.0.71:5432/mss-parse-log_0
username: postgres
password: OxwN4u9pzlX5PVQMFE1sYuRykhqorB
driverClassName: org.postgresql.Driver
dataSourceClassName: org.postgresql.ds.PGSimpleDataSource
ds_1:
url: jdbc:postgresql://10.100.0.71:5432/mss-parse-log_1
username: postgres
password: OxwN4u9pzlX5PVQMFE1sYuRykhqorB
driverClassName: org.postgresql.Driver
dataSourceClassName: org.postgresql.ds.PGSimpleDataSource
rules:
- !SHARDING
tables:
t_norm_event:
actualDataNodes: ds_${0…1}.t_norm_event_${0…1}
tableStrategy:
standard:
shardingColumn: id
shardingAlgorithmName: t_norm_event_inline
keyGenerateStrategy:
column: id
keyGeneratorName: snowflake
shardingAlgorithms:
t_norm_event_inline:
type: INLINE
props:
algorithm-expression: t_norm_event_${id % 2}
keyGenerators:
snowflake:
type: SNOWFLAKE
props:
worker-id: 123
这是代码:
package org.example;
import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class CustomPostgresSinkTest {
public static void main(String[] args) {
File configFile = new File("D:/work-project/towere/mss-log-normalize/src/main/resources/shardingsphere-config.yml");
try {
// 创建 ShardingSphere 数据源
DataSource dataSource = YamlShardingSphereDataSourceFactory.createDataSource(configFile);
// 插入数据
insertData(dataSource);
System.out.println("数据插入完成!");
} catch (IOException | SQLException e) {
e.printStackTrace();
}
}
private static void insertData(DataSource dataSource) throws SQLException {
String insertSQL = "INSERT INTO t_norm_event (id, event_name, event_time) VALUES (?, ?, ?)";
try (Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement(insertSQL)) {
// 插入10条示例数据
for (int i = 1; i <= 10; i++) {
pstmt.setLong(1, i); // 分片键
pstmt.setString(2, "事件-" + i);
pstmt.setTimestamp(3, new java.sql.Timestamp(System.currentTimeMillis()));
pstmt.addBatch();
}
int[] results = pstmt.executeBatch();
System.out.println("插入行数: " + results.length);
} catch (SQLException e) {
System.err.println("插入数据失败: " + e.getMessage());
}
}
}