springboot使用多数据源

在第一篇简单介绍了关于springboot的一些东西,现在开始慢慢进入高级一点的东西。一般的简单,比较小型的项目用到的数据库就一个,采用多个表来处理业务。但是当业务复杂一点,你可能就需要使用多数据源。由于业务的要求,你得使用不同的数据源。本人见过复杂的项目使用了十多个数据源,不过一般的用两个三个就OK。好了,开始咱们的代码。

package microservice.com.config;

import java.io.InputStream;
import java.util.Properties;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

/**
 * 数据源配置
 *
 * @author 肖云鹤
 * 2016年12月10日
 */
@Configuration
public class DataSourceConfig {
   
    /**
     * ͬwhite数据源
     */
    @Bean(name="whiteDataSource", destroyMethod="close")
    @Qualifier("whiteDataSource")
    @Primary    //使用多数据源时需要加上这个注解
    public DruidDataSource whiteDataSource() throws Exception {
        InputStream is = null;
        Properties props = null;
       
        try {
            is = this.getClass().getClassLoader().getResourceAsStream("datasource.white.properties");
            props = new Properties();
            props.load(is);
           
        } finally {
            if (is != null) is.close();
        }
       
        DruidDataSource ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(props);
        return ds;
    }
   
    /**
     * me数据源
     */
    @Bean(name="meDataSource", destroyMethod="close")
    @Qualifier("meDataSource")
    public DruidDataSource meDataSource() throws Exception {
        InputStream is = null;
        Properties props = null;
       
        try {
            is = this.getClass().getClassLoader().getResourceAsStream("datasource.me.properties");
            props = new Properties();
            props.load(is);
        } finally {
            if (is != null) is.close();
        }
       
        DruidDataSource ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(props);
        return ds;
    }
   
    /**
     * 考试监管数据源
     */
    @Bean(name="xyDataSource", destroyMethod="close")
    @Qualifier("xyDataSource")
    public DruidDataSource xyDataSource() throws Exception {
        InputStream is = null;
        Properties props = null;
       
        try {
            is = this.getClass().getClassLoader().getResourceAsStream("datasource.xy.properties");
            props = new Properties();
            props.load(is);
        } finally {
            if (is != null) is.close();
        }
       
        DruidDataSource ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(props);
        return ds;
    }
   
    /**
     * white Jdbc
     */
    @Bean(name="whiteJdbc")
    public JdbcTemplate whiteJdbc(@Qualifier("whiteDataSource")DruidDataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
   
    /**
     * 书城Jdbc
     */
    @Bean(name="meJdbc")
    public JdbcTemplate meJdbc(@Qualifier("meDataSource")DruidDataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
   
    /**
     * 校园易商城Jdbc
     */
    @Bean(name="xyJdbc")
    public JdbcTemplate xyJdbc(@Qualifier("xyDataSource")DruidDataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}
上面的是使用的spring自带的jdbctemple,我采用的是阿里巴巴的数据源,它自带加密工具。将datasource注入。需要注意的是 @Primary 这个注解,对同一个接口,可能会有几种不同的实现类,默认的采用一种实现。


driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/white
username=root
password=bNVOqb7WKLX5Bjnw+LMv92taj25KOxDimXxILPQjw42wgv+1lHzOH8kr97xDwWdhpY67QuYCS7sWN4W46YbkFA==
initialSize=1
maxActive=10
minIdle=3
maxWait=60000
removeAbandoned=true
removeAbandonedTimeout=180
timeBetweenEvictionRunsMills=60000
minEvictableIdleTimeMills=300000
validationQuery=select 1 from dual
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=true
maxPoolPreparedStatementPerConnectionSize=50
filters=config,stat
connectionProperties=config.decrypt=true

这是我的数据源配置,你可以自行修改。也可以只是用账号,密码等简单的配置。

现在来使用Spring的JDBCtemple


@Component
public class meDao {
   
    @Autowired
    @Qualifier("meJdbc")
    private JdbcTemplate jdbc;
}

这里就注入了jdbc,使用的时候也挺方便。封装了基本的增删改查,批量查询等等。

    /**依据所有的查询用户*/
    public List<User> queryUserAll(){
       
        List <User> list = new ArrayList<User>();
        List<Map <String, Object>> result = jdbc.queryForList(allSql);
        for (Map <String, Object> map :result){
            User user = new User();
            user.setAddress((String) map.get("address"));
            user.setBuyername((String) map.get("buyername"));
            user.setEmail((String) map.get("email"));
            user.setRealname((String) map.get("realname"));
            user.setBuyerjf((int) map.get("buyerjf"));
            list.add(user);
        }
       
        return list;
    }

这里查询所有的用户,和你平时使用原生的JDBC操作类似,想要深入了解jdbcTemple可以看看Api。

基本上以上就是一个多数据源的配置。

猜你喜欢

转载自jifengjianhao.iteye.com/blog/2348392