# dbRouter **Repository Path**: guo_zi_feng/db-router ## Basic Information - **Project Name**: dbRouter - **Description**: No description available - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-11-16 - **Last Updated**: 2023-11-24 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # dbRouter #### 测试 先install本工程,然后拉取 https://gitee.com/guo_zi_feng/dbRouter-test #### 分库原理 spring-jdbc的包中,提供了AbstractRoutingDataSource用于数据源路由操作 该类实现了InitializingBean接口,说明初始化时会调用afterPropertiesSet方法 ```java @Override public void afterPropertiesSet() { //targetDataSources是一个Map,实际上是 if (this.targetDataSources == null) { throw new IllegalArgumentException("Property 'targetDataSources' is required"); } this.resolvedDataSources = CollectionUtils.newHashMap(this.targetDataSources.size()); this.targetDataSources.forEach((key, value) -> { Object lookupKey = resolveSpecifiedLookupKey(key); //可以看到这里把他转回了DataSource类型 DataSource dataSource = resolveSpecifiedDataSource(value); this.resolvedDataSources.put(lookupKey, dataSource); }); if (this.defaultTargetDataSource != null) { this.resolvedDefaultDataSource = resolveSpecifiedDataSource(this.defaultTargetDataSource); } } ``` 该抽象类拥有一个唯一的抽象方法 ```java /** * Determine the current lookup key. This will typically be * implemented to check a thread-bound transaction context. *

Allows for arbitrary keys. The returned key needs * to match the stored lookup key type, as resolved by the * {@link #resolveSpecifiedLookupKey} method. */ @Nullable protected abstract Object determineCurrentLookupKey(); ``` 在determineTargetDataSource方法中调用了该抽象方法 ```java protected DataSource determineTargetDataSource() { Assert.notNull(this.resolvedDataSources, "DataSource router not initialized"); //由我们实现,其实就是把要切换的key给他,他会去map里获取相应的数据源 Object lookupKey = determineCurrentLookupKey(); DataSource dataSource = this.resolvedDataSources.get(lookupKey); if (dataSource == null && (this.lenientFallback || lookupKey == null)) { dataSource = this.resolvedDefaultDataSource; } if (dataSource == null) { throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]"); } return dataSource; } ``` 主要逻辑在com.pj.DBRouterJoinPoint