001/** 002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package io.jboot.db.datasource; 017 018import com.jfinal.kit.PathKit; 019import io.jboot.core.spi.JbootSpiLoader; 020import io.jboot.exception.JbootException; 021import io.jboot.support.seata.JbootSeataManager; 022import io.jboot.utils.StrUtil; 023import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory; 024 025import javax.sql.DataSource; 026import java.io.File; 027 028 029public class DataSourceBuilder { 030 031 private DataSourceConfig config; 032 033 public DataSourceBuilder(DataSourceConfig datasourceConfig) { 034 this.config = datasourceConfig; 035 } 036 037 public DataSource build() { 038 039 String shardingConfigYaml = config.getShardingConfigYaml(); 040 041 // 不启用分库分表的配置 042 if (StrUtil.isBlank(shardingConfigYaml)) { 043 DataSource ds = createDataSource(config); 044 return JbootSeataManager.me().wrapDataSource(ds); 045 } 046 047 048 File yamlFile = shardingConfigYaml.startsWith(File.separator) 049 ? new File(shardingConfigYaml) 050 : new File(PathKit.getRootClassPath(), shardingConfigYaml); 051 052 try { 053// return YamlShardingDataSourceFactory.createDataSource(yamlFile); 054 return YamlShardingSphereDataSourceFactory.createDataSource(yamlFile); 055 } catch (Exception e) { 056 throw new JbootException(e); 057 } 058 } 059 060 061 private DataSource createDataSource(DataSourceConfig dsc) { 062 063 String factory = dsc.getFactory(); 064 if (StrUtil.isBlank(factory)) { 065 return new HikariDataSourceFactory().createDataSource(dsc); 066 } 067 068 switch (factory) { 069 case "hikari": 070 case "hikariCP": 071 case "hikaricp": 072 return new HikariDataSourceFactory().createDataSource(dsc); 073 case "druid": 074 return new DruidDataSourceFactory().createDataSource(dsc); 075 default: 076 DataSourceFactory dataSourceFactory = JbootSpiLoader.load(DataSourceFactory.class, factory); 077 if (dataSourceFactory == null) { 078 throw new NullPointerException("Can not load DataSourceFactory spi for name: " + factory); 079 } 080 return dataSourceFactory.createDataSource(dsc); 081 } 082 } 083}