第十六周总结
Java 学习第十六周总结
一、学习概述
本周聚焦分布式数据库与现代数据管理技术,深入学习数据库分区与分片、NoSQL 与 NewSQL 技术、分布式事务处理、云数据库服务及数据仓库架构。通过理论与实践结合,掌握分布式系统设计、数据库中间件应用、备份恢复策略及云原生数据库最佳实践,为构建大规模数据系统奠定基础。
二、分布式数据库技术
- 数据库分区与分片
分区技术实践
-- 范围分区(按日期分区)
CREATE TABLE sales (
id INT PRIMARY KEY,
amount DECIMAL(10,2),
sale_date DATE
)
PARTITION BY RANGE (YEAR(sale_date)) (
PARTITION p2022 VALUES LESS THAN (2023),
PARTITION p2023 VALUES LESS THAN (2024),
PARTITION p2024 VALUES LESS THAN MAXVALUE
);
-- 哈希分区(按用户ID哈希)
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(50),
reg_date DATE
)
PARTITION BY HASH(id)
PARTITIONS 4;
分片架构示例
ShardingSphere分片配置
datasource:
ds0:
url: jdbc:mysql://localhost:3306/ds0
username: root
password: root
ds1:
url: jdbc:mysql://localhost:3306/ds1
username: root
password: root
sharding:
tables:
order:
actual-data-nodes: ds${0..1}.order_${1..2}
table-strategy:
inline:
sharding-column: user_id
algorithm-expression: order_${user_id % 2 + 1}
key-generator:
column: order_id
type: SNOWFLAKE
2. NoSQL 与 NewSQL 技术
MongoDB 文档数据库
// 插入文档
db.users.insertOne({
name: "Alice",
age: 28,
email: "alice@example.com",
address: {
city: "Beijing",
province: "Beijing"
}
});
// 查询文档
db.users.find({ age: { $gt: 25 } }).sort({ name: 1 });
// 创建索引
db.users.createIndex({ name: 1, age: -1 });
HBase 列族数据库
// 创建表
Admin admin = connection.getAdmin();
HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf("users"));
tableDesc.addFamily(new HColumnDescriptor("cf1"));
tableDesc.addFamily(new HColumnDescriptor("cf2"));
admin.createTable(tableDesc);
// 插入数据
Put put = new Put(Bytes.toBytes("user1"));
put.addColumn(Bytes.toBytes("cf1"), Bytes.toBytes("name"), Bytes.toBytes("Bob"));
put.addColumn(Bytes.toBytes("cf2"), Bytes.toBytes("age"), Bytes.toBytes(30));
table.put(put);
三、数据库中间件与事务处理
- 数据库中间件应用
MyBatis 持久层框架
// Mapper接口
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User findById(Long id);
@Insert("INSERT INTO users(name, age) VALUES(#{name}, #{age})")
int insert(User user);
}
// 配置文件