背景
最近项目中为了提高数据库读写速度,想要横向扩展Oracle数据库,一个Master,多个Slave。master可以读写数据,Slave只能读数据。这就是多数据源问题了。怎么利用Spring解决这个问题呢?
测试代码
1. pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
2. 定义两个数据源名字
public enum ClientDatabase {
CLIENT_A, CLIENT_B
}
3、利用Threadlocal 数据源的名字绑定到当前执行的线程上
public class ClientDatabaseContextHolder {
private static ThreadLocal<ClientDatabase> CONTEXT= new ThreadLocal<>();
public static void set(ClientDatabase clientDatabase) {
Assert.notNull(clientDatabase, "clientDatabase cannot be null");
CONTEXT.set(clientDatabase);
}
public static ClientDatabase getClientDatabase() {
return CONTEXT.get();
}
public static void clear() {
CONTEXT.remove();
}
}
4. 继承AbstractRoutingDataSource ,Spring会在取数据源之前调用determineCurrentLookupKey方法取数据源的名字,通过数据源的名字查找数据源。这样就可以实现动态更改数据源了。readonly事务的时候,就可以切换到读的那个数据库了。
public class ClientDataSourceRouter extends AbstractRoutingDataSource {
private static final Logger log = LoggerFactory.getLogger(ClientDataSourceRouter.class);
@Override
protected Object determineCurrentLookupKey() {
ClientDatabase clientDatabase = ClientDatabaseContextHolder.getClientDatabase();
if (clientDatabase != null) { //有指定切换数据源切换的时候,才给输出日志 并且也只给输出成debug级别的 否则日志太多了
log.info("线程[{}],此时切换到的数据源为:{}", Thread.currentThread().getId(), clientDatabase);
}
return clientDatabase;
}
}
5. 定义两个数据源,不同的H2数据库。
@Configuration
public class RoutingTestConfiguration {
@Autowired
private ClientADetails clientADetails;
@Autowired
private ClientBDetails clientBDetails;
@Bean
public DataSource clientDatasource() {
Map<Object, Object> targetDataSources = new HashMap<>();
DataSource clientADatasource = clientADatasource();
DataSource clientBDatasource = clientBDatasource();
targetDataSources.put(ClientDatabase.CLIENT_A, clientADatasource);
targetDataSources.put(ClientDatabase.CLIENT_B, clientBDatasource);
ClientDataSourceRouter clientRoutingDatasource = new ClientDataSourceRouter();
clientRoutingDatasource.setTargetDataSources(targetDataSources);
clientRoutingDatasource.setDefaultTargetDataSource(clientADatasource);
return clientRoutingDatasource;
}
private DataSource clientADatasource() {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
return dbBuilder.setType(EmbeddedDatabaseType.H2).setName(clientADetails.getName())
.addScript(clientADetails.getScript()).build();
}
private DataSource clientBDatasource() {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
return dbBuilder.setType(EmbeddedDatabaseType.H2).setName(clientBDetails.getName())
.addScript(clientBDetails.getScript()).build();
}
}
6.? 创建两个类取两个数据的名字等等。
@Component
@ConfigurationProperties(prefix = "client-a.datasource")
public class ClientBDetails {
private String name = "CLIENT_B";
private String script = "SOME_SCRIPT.sql";
// Getters & Setters
}
@Component
@ConfigurationProperties(prefix = "client-a.datasource")
public class ClientADetails {
private String name = "CLIENT_A";
private String script = "SOME_SCRIPT.sql";
// Getters & Setters
}
7. application.properties
#database details for CLIENT_A
client-a.datasource.name=CLIENT_A
client-a.datasource.script=SOME_SCRIPT.sql
#database details for CLIENT_B
client-b.datasource.name=CLIENT_B
client-b.datasource.script=SOME_SCRIPT.sql
8.? 测试类
@SpringJUnitConfig
@ContextConfiguration(classes = {RoutingTestConfiguration.class, ClientBDetails.class, ClientADetails.class})
public class TestSpringBean {
@Autowired
private DataSource dataSource;
@Test
public void test1() throws SQLException {
System.out.println(dataSource.getConnection());
ClientDatabaseContextHolder.set(ClientDatabase.CLIENT_B);
System.out.println(dataSource.getConnection());
}
}
执行结果
conn2: url=jdbc:h2:mem:CLIENT_A user=SA
19:29:04.576 [main] INFO ClientDataSourceRouter - 线程[1],此时切换到的数据源为:CLIENT_B
[jdbc:h2:mem:CLIENT_B;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false]
conn3: url=jdbc:h2:mem:CLIENT_B user=SA
|