spring-boot 之 使員Druid 整合Mybatis 最簡配置多數據源
在實際開發過程中,同一個項目很可能需要多個數據源進行支持,所以今天我把自己整合Mybatis多數據源的過程和大家分享下。
添加所需依賴
<!--mysql連接驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--通用mapper -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
<!--druid數據源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.25</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
這裡為了測試方便引用了Mybatis通用mapper插件,只適合對單表的增刪改進行操作,避免了xml的配置和手寫sql,特別方便。大家也可以利用常規方式進行測試,這裡不做過多解釋。在application.properties配置文件進行相關配置。我們配置了兩個數據源,一個作為主數據源,另一個作為從數據源。
# master 主數據源配置
master.datasource.url=jdbc:mysql://localhost/master?useUnicode=true&characterEncoding=utf8
master.datasource.username=root
master.datasource.password=root
master.datasource.driverClassName=com.mysql.jdbc.Driver
# cluster 從數據源配置
cluster.datasource.url=jdbc:mysql://localhost/cluster?useUnicode=true&characterEncoding=utf8
cluster.datasource.username=root
cluster.datasource.password=root
cluster.datasource.driverClassName=com.mysql.jdbc.Driver
#連接池的配置信息
## 初始化大小,最小,最大
spring.druid.initialSize=5
spring.druid.minIdle=5
spring.druid.maxActive=20
## 配置獲取連接等待超時的時間
spring.druid.maxWait=60000
# 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒
spring.druid.timeBetweenEvictionRunsMillis=60000
# 配置一個連接在池中最小生存的時間,單位是毫秒
spring.druid.minEvictableIdleTimeMillis=300000
spring.druid.validationQuery=SELECT 1 FROM DUAL
spring.druid.testWhileIdle=true
spring.druid.testOnBorrow=false
spring.druid.testOnReturn=false
spring.druid.poolPreparedStatements=true
spring.druid.maxPoolPreparedStatementPerConnectionSize=20
# 配置監控統計攔截的filters,去掉後監控界面sql無法統計,"wall"用於防火牆
spring.druid.filters=stat,wall,log4j
# 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
spring.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
主數據源的配置文件:
@Configuration
// 掃描 Mapper
@MapperScan(basePackages = MasterDataSourceConfig.MASTER_PACKAGE, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {
//掃描從數據源mapper介面所在的包
static final String MASTER_PACKAGE = "cn.jj.mapper.master";
//掃描從數據源xml文件
static final String MAPPER_LOCATION = "classpath:mapper/master/*.xml";
@Value("${master.datasource.url}")
private String url;
@Value("${master.datasource.username}")
private String user;
@Value("${master.datasource.password}")
private String password;
@Value("${master.datasource.driverClassName}")
private String driverClass;
@Bean(name = "masterDataSource")
@Primary
public DataSource masterDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "masterTransactionManager")
@Primary
public DataSourceTransactionManager masterTransactionManager() {
return new DataSourceTransactionManager(masterDataSource());
}
@Bean(name = "masterSqlSessionFactory")
@Primary
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(masterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(MasterDataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
從數據源配置文件:
@Configuration
//掃描 Mapper
@MapperScan(basePackages = ClusterDataSourceConfig.CLASTER_PACKAGE, sqlSessionFactoryRef = "clusterSqlSessionFactory")
public class ClusterDataSourceConfig {
//掃描從數據源mapper介面所在的包
static final String CLASTER_PACKAGE = "cn.jj.mapper.cluster";
//掃描從數據源xml文件
static final String MAPPER_LOCATION = "classpath:mapper/cluster/*.xml";
@Value("${cluster.datasource.url}")
private String url;
@Value("${cluster.datasource.username}")
private String user;
@Value("${cluster.datasource.password}")
private String password;
@Value("${cluster.datasource.driverClassName}")
private String driverClass;
@Bean(name = "clusterDataSource")
public DataSource clusterDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "clusterTransactionManager")
public DataSourceTransactionManager clusterTransactionManager() {
return new DataSourceTransactionManager(clusterDataSource());
}
@Bean(name = "clusterSqlSessionFactory")
public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(clusterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(ClusterDataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
項目結構:
到這裡Mybatis多數據源已經配置好,需要注意的是,主,從數據源一定要配置正確,特別是以下位置一定要和工程目錄對應正確。
資料庫數據信息
主資料庫:
從資料庫:
編寫測試類測試
@RunWith(SpringRunner.class)
@SpringBootTest
public class MapperTest2 {
@Autowired
private CityService cityService;
@Autowired
private UserService userService;
// 查詢主表
@Test
public void selectCity() {
List<City> city = cityService.selectAll();
System.out.println("主表信息如下:");
for (City city2 : city) {
System.out.println(
"id:"+ city2.getId() + " " + "name:" + city2.getName() + " " + "state:" + city2.getState());
}
}
// 查詢從表
@Test
public void selectUser() {
try {
List<User> user = userService.searchAll();
System.out.println("從表信息如下:");
for (User user2 : user) {
System.out.println("id:"+user2.getId() + " " + user2.getGender() + " " + user2.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
控制台輸出信息如下:
spring boot 整合Mabatis 配置多數據源完成。
TAG:程序員小新人學習 |