Nói về cách sử dụng đơn giản của Sharding-Jdbc - f8betv0
Trong công việc hàng ngày, chúng ta thường sử dụng nhiều thành phần chia cơ sở dữ liệu và bảng. Một trong những công cụ nổi bật là Sharding-Jdbc, ban đầu được phát triển bởi Dangdang và sau đó đã được đóng góp cho Apache. Bài viết này sẽ trình bày cách sử dụng đơn giản của nó, đặc biệt tập trung vào cấu hình bằng Java Config thay vì cách truyền thống dựa trên XML hoặc properties.
Đầu tiên, bạn cần tạo một dự án Spring Boot thông qua Spring Initializr với sự hỗ trợ của JDBC. Sau khi tạo xong, hãy thêm phụ thuộc chính sau vào tệp pom.xml:
1<dependency>
2 <groupId>org.apache.shardingsphere</groupId>
3 <artifactId>shardingsphere-jdbc-core</artifactId>
4 <version>5.0.0-beta</version>
5</dependency>
Vì Spring Boot có khả năng tự động tải các cấu hình liên quan đến DataSource, để tránh xung đột, bạn cần loại bỏ quá trình tự động này tại điểm khởi chạy ứng dụng như sau:
1@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
2public class ShardingJdbcDemoApplication implements CommandLineRunner {
3 // Code tiếp theo...
4}
Tiếp theo, chúng ta sẽ thực hiện cấu hình chi tiết bằng Java Đăng Nhập Xda77 Config. Dưới đây là đoạn mã cấu hình nguồn dữ liệu cùng với quy tắc phân mảnh:
1@Configuration
2public class MysqlConfig {
3
4 @Bean
5 public DataSource dataSource() throws SQLException {
6 // Cấu hình nguồn dữ liệu thực tế
7 Map<String, DataSource> dataSourceMap = new HashMap<>();
8
9 // Thiết lập nguồn dữ liệu đầu tiên sử dụng HikariCP
10 HikariDataSource dataSource1 = new HikariDataSource();
11 dataSource1.setDriverClassName("com.mysql.jdbc.Driver");
12 dataSource1.setJdbcUrl("jdbc:mysql://localhost:3306/sharding");
13 dataSource1.setUsername("username");
14 dataSource1.setPassword("password");
15
16 dataSourceMap.put("ds0", dataSource1);
17
18 // Cấu hình quy tắc phân bảng cho bảng student
19 ShardingTableRuleConfiguration studentTableRuleConfig =
20 new ShardingTableRuleConfiguration("student", "ds0.student_$->{0..1}");
21
22 // Đặt chiến lược phân bảng dựa trên trường user_id
23 studentTableRuleConfig.setTableShardingStrategy(
24 new StandardShardingStrategyConfiguration("user_id", "tableShardingAlgorithm"));
25
26 // Tạo quy tắc phân mảnh
27 ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
28 shardingRuleConfig.getTables().add(studentTableRuleConfig);
29
30 // Cấu hình thuật toán phân bảng
31 Properties tableShardingAlgorithmProps = new Properties();
32 tableShardingAlgorithmProps.setProperty("algorithm-expression", "student_${user_id % 2}");
33 shardingRuleConfig.getShardingAlgorithms().put("tableShardingAlgorithm",
34 new ShardingSphereAlgorithmConfiguration("INLINE", tableShardingAlgorithmProps));
35
36 // Trả về nguồn dữ liệu được cấu hình sẵn
37 return ShardingSphereDataSourceFactory.createDataSource(dataSourceMap,
38 Collections.singleton(shardingRuleConfig), new Properties());
39 }
40}
Sau khi hoàn tất cấu hình, bạn có thể sử dụng nguồn dữ liệu này để truy vấn dữ liệu từ hai bảng student_0
và student_1
. Dưới đây là ví dụ về cách thực hiện truy vấn:
1@Override
2public void run(String... args) {
3 LOGGER.info("Chạy chương trình...");
4
5 String sql = "SELECT * FROM student WHERE user_id=?";
6
7 try (
8 Connection conn = dataSource.getConnection();
9 PreparedStatement ps = conn.prepareStatement(sql)
10 ) {
11 // Truy vấn dữ liệu từ bảng student_1 (user_id lẻ)
12 ps.setInt(1, 1001);
13 ResultSet resultSet = ps.executeQuery();
14
15 while (resultSet.next()) {
16 int id = resultSet.getInt("id");
17 String name = resultSet.getString("name");
18 int userId = resultSet.getInt("user_id");
19 int age = resultSet.getInt("age");
20
21 System.out.println("Bảng lẻ - ID: " + id + ", Họ tên: " + name
22 + ", User ID: " + userId + ", Tuổi: " + age);
23 System.out.println("=============================");
24 }
25
26 // Truy vấn dữ liệu từ bảng student_0 [những game nổ hũ uy tín](/post/68d7a7d1676e1ca6.html) (user_id chẵn)
27 ps.setInt(1, 1000);
28 resultSet = ps.executeQuery();
29
30 while (resultSet.next()) {
31 int id = resultSet.getInt("id");
32 String name = resultSet.getString("name");
33 int userId = resultSet.getInt("user_id");
34 int age = resultSet.getInt("age");
35
36 System.out.println("Bảng chẵn - ID: " + id + ", Họ tên: " + name
37 + ", User ID: " + userId + ", Tuổi: " + age);
38 System.out.println("=============================");
39 } [f8betv0](/post/f5de71a60c733e26.html)
40 } catch (SQLException e) {
41 e.printStackTrace();
42 }
43}
Kết quả truy vấn sẽ hiển thị dữ liệu từ hai bảng khác nhau tùy thuộc vào giá trị của user_id
. Nếu user_id
là số lẻ, dữ liệu sẽ được lấy từ bảng student_1
, còn nếu là số chẵn thì từ bảng student_0
.
Hy vọng bài viết này giúp bạn hiểu rõ hơn về cách cấu hình và sử dụng Sharding-JDBC bằng Java Config trong dự án Spring Boot!