springboot3读写分离
原创2021年11月29日大约 1 分钟
温馨提示
源码:https://github.com/ChenSino/shardingsphere
mysql读写分离搭建请参考mysql主从复制搭建
1. maven依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.9</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.2.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
~~~
### 2. application.yml配置
~~~yaml
server:
port: 8088
spring:
shardingsphere:
datasource:
names: ds0, ds1
ds0:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.Driver
url: jdbc:mysql://192.168.1.150:33061/test_db?serverTimezone=UTC&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
ds1:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.Driver
url: jdbc:mysql://192.168.1.150:33061/test_db?serverTimezone=UTC&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
props:
sql-show: true
rules:
readwrite-splitting:
data-sources:
my_ds: # 自定义的数据源名称
static-strategy:
write-data-source-name: ds0 # 指定写入数据源
read-data-source-names: ds1 # 指定读取数据源列表
3.测试代码
import com.chen.demo.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@MapperScan(basePackages = "com.chen.demo.mapper")
class DemoApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
User user = userMapper.selectById(1);
System.out.println(user);
}
@Test
void add() {
User user = new User();
user.setName("Jack");
userMapper.insert(user);
System.out.println(user.getId());
}
}
//Mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.chen.demo.User;
import org.apache.ibatis.annotations.Mapper;
/**
* @author chenkun
* @description:
* @date: 2024-11-28 11:56:05
**/
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
//entity
@Data
@TableName("user")
public class User {
private Integer id;
private String name;
}