将一个druid-springboot-starter的springboot项目转换成使用shardingjdbc的springboot项目
时间: 2023-10-20 18:35:33 浏览: 118
将一个druid-springboot-starter的springboot项目转换成使用shardingjdbc的springboot项目的步骤如下:
1. 在pom.xml文件中增加sharding-jdbc-spring-boot-starter和mysql-connector-java的依赖。
```xml
<dependency>
<groupId>io.shardingjdbc</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>${shardingjdbc.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
```
2. 在application.yml或application.properties中配置sharding-jdbc的数据源和分库分表规则。
```yaml
spring:
shardingsphere:
datasource:
names: ds0, ds1 # 数据源名称
ds0:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/db0?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
ds1:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
sharding:
tables:
t_order:
actual-data-nodes: ds$->{0..1}.t_order_$->{0..1}
table-strategy:
inline:
sharding-column: order_id
algorithm-expression: t_order_$->{order_id % 2}
key-generator:
type: SNOWFLAKE
column: order_id
binding-tables: t_order
default-database-strategy:
inline:
sharding-column: user_id
algorithm-expression: ds$->{user_id % 2}
default-table-strategy:
none:
```
3. 在代码中使用sharding-jdbc的数据源访问数据库。
```java
@Autowired
private JdbcTemplate jdbcTemplate;
public void query() {
String sql = "select * from t_order where user_id = ?";
List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql, 10);
System.out.println(resultList);
}
```
通过以上步骤,就可以将一个druid-springboot-starter的springboot项目转换成使用shardingjdbc的springboot项目了。
阅读全文