SpringBoot(三):多数据源配置
简介
说起多数据源,一般都来解决那些问题呢,主从模式或者业务比较复杂需要连接不同的分库来支持业务,配置多数据源重点是配置文件,所以数据库,pox文件,实体类我都不发出来了,自己创建两个数据库,配置实体类就行了
本作品采用<a rel="license" href="http://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>进行许可。
版权声明:本文由 低调小熊猫 发表于 低调小熊猫的博客
转载声明:自由转载-非商用-非衍生-保持署名,非商业转载请注明作者及出处,商业转载请联系作者本人qq:2696284032
文章链接:https://aodeng.cc/archives/springboot-san
单纯的广告
个人博客:https://aodeng.cc
微信公众号:低调小熊猫
qq交流群:756796932
排除自动配置
springboot会自动读取配置文件,由于我们需要配置多数据源,所以要排除自动配置,在启动入口添加如下注解
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
配置数据源
在application.yml中配置两个数据源
spring:
datasource:
first:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/XXX?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: XXX
password: XXX
type: com.alibaba.druid.pool.DruidDataSource
initial-size: 1
minIdle: 3
maxActive: 20
maxWait: 60000
filters: stat,wall,slf4j
second:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/XXX?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: XXX
password: XXX
type: com.alibaba.druid.pool.DruidDataSource
创建配置文件封装类
@ConfigurationProperties注解指定数据来源
1.FirstDataProperties类
package com.ad.core.hope.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @program:hope
* @author:aodeng
* @create:2018-08-31 13:46
**/
@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.first")
public class FirstDataProperties {
String driverClassName;
String url;
String username;
String password;
}
2.SecondDataProperties类
package com.ad.core.hope.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @program:hope
* @author:aodeng
* @create:2018-08-31 13:47
**/
@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.second")
public class SecondDataProperties {
String driverClassName;
String url;
String username;
String password;
}
数据源配置
这里面的代码才是最重要的
注:@Primary必须使用该注解指定主数据源
@MapperScan指定路径下的mapper使用该数据源
1.FirstDataSourceConfig配置
package com.ad.core.hope.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
* @program:hope
* @author:aodeng
* @create:2018-08-02 20:16
**/
@Configuration
@MapperScan(basePackages = "com.ad.core.hope.mapper.first",sqlSessionTemplateRef = "firstSqlSessionTemplate")
public class FirstDataSourceConfig {
@Autowired
private FirstDataProperties firstprop;
//创建数据源
@Bean(name="firstDataSource")
@ConfigurationProperties(prefix = "spring.datasource.first")
public DataSource getFirstDataSource(){
DataSource build = DataSourceBuilder.create()
.driverClassName(firstprop.driverClassName)
.url(firstprop.url)
.username(firstprop.username)
.password(firstprop.password).build();
return build;
}
//创建SqlSessionFactory
@Bean(name = "firstSqlSessionFactory")
public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource) throws Exception{
SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
//创建事务管理器
@Bean(name = "firstTransactionManager")
public DataSourceTransactionManager firstTransactionManager(@Qualifier("firstDataSource") DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
//创建SqlSessionTemplate
@Bean(name = "firstSqlSessionTemplate")
public SqlSessionTemplate firstSqlSessionTemplate(@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception{
return new SqlSessionTemplate(sqlSessionFactory);
}
private Class getType(String type){
try {
return Class.forName(type);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
return null;
}
}
2.SecondDataSourceConfig配置
package com.ad.core.hope.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
* @program:hope
* @author:aodeng
* @create:2018-08-02 20:16
**/
@Configuration
@MapperScan(basePackages = "com.ad.core.hope.mapper.second",sqlSessionTemplateRef = "secondSqlSessionTemplate")
public class SecondDataSourceConfig {
@Autowired
private SecondDataProperties secondprop;
//创建数据源
@Bean(name="secondDataSource")
@ConfigurationProperties(prefix = "spring.datasource.second")
@Primary
public DataSource getSecondDataSource(){
DataSource build = DataSourceBuilder.create()
.driverClassName(secondprop.driverClassName)
.url(secondprop.url)
.username(secondprop.username)
.password(secondprop.password).build();
return build;
}
//创建SqlSessionFactory
@Bean(name = "secondSqlSessionFactory")
@Primary
public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception{
SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
}
//创建事务管理器
@Bean(name = "secondTransactionManager")
@Primary
public DataSourceTransactionManager secondTransactionManager(@Qualifier("secondDataSource") DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
//创建SqlSessionTemplate
@Bean(name = "secondSqlSessionTemplate")
@Primary
public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception{
return new SqlSessionTemplate(sqlSessionFactory);
}
private Class getType(String type){
try {
return Class.forName(type);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
return null;
}
}
实现Mapper
注:该mapper的路径必须和@MapperScan注解的指定路径一样
1.first路径下的mapepr
package com.ad.core.hope.mapper.first;
import com.ad.core.hope.enums.TestUserEnum;
import com.ad.core.hope.vo.base.TestVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface TestInterface {
@Select("SELECT * FROM user")
@Results({
@Result(property = "sex", column = "sex", javaType = TestUserEnum.class),
@Result(property = "name", column = "username")
})
List<TestVo> getAll();
}
2.second路径下的mapper
package com.ad.core.hope.mapper.second;
import com.ad.core.hope.model.admin.SysUser;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* @program:hope
* @author:aodeng
* @create:2018-09-02 17:25
**/
@org.apache.ibatis.annotations.Mapper
public interface TestMapper{
@Select("SELECT * FROM sys_user")
@Results({
@Result(property = "userid", column = "userId"),
@Result(property = "username", column = "username")
})
List<SysUser> getAll();
}
Controller使用
使用@Autowired注解装配mapper使用
@Controller
public class TeseController {
@Autowired
private TestInterface testInterface;
@Autowired
private TestMapper testMapper;
@RequestMapping("/login")
public String login(Model model){
//数据源first测试
List<TestVo> list=testInterface.getAll();
for(int i=0;i<list.size();i++){
System.out.println("测试fisrt数据源"+list.get(i).getName());
}
//数据源second测试
List<SysUser> user=testMapper.getAll();
for(int i=0;i<user.size();i++){
System.out.println("测试second数据源"+user.get(i).getUsername());
}
return "admin/system_login";
}
}