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.alibaba.druid.pool.DruidDataSource;
019import com.google.common.collect.Sets;
020import com.jfinal.log.Log;
021
022import javax.sql.DataSource;
023import java.sql.SQLException;
024
025/**
026 * @author Michael Yang 杨福海 (fuhai999@gmail.com)
027 * @version V1.0
028 */
029public class DruidDataSourceFactory implements DataSourceFactory {
030
031    static Log log = Log.getLog(DruidDataSourceFactory.class);
032
033    @Override
034    public DataSource createDataSource(DataSourceConfig config) {
035
036        DruidDataSource druidDataSource = new DruidDataSource();
037        druidDataSource.setUrl(config.getUrl());
038        druidDataSource.setUsername(config.getUser());
039        druidDataSource.setPassword(config.getPassword());
040        druidDataSource.setDriverClassName(config.getDriverClassName());
041        druidDataSource.setMaxActive(config.getMaximumPoolSize());
042        druidDataSource.setMaxWait(config.getMaxWait());
043        druidDataSource.setTimeBetweenEvictionRunsMillis(config.getTimeBetweenEvictionRunsMillis());
044        druidDataSource.setMinEvictableIdleTimeMillis(config.getMinEvictableIdleTimeMillis());
045        druidDataSource.setTimeBetweenConnectErrorMillis(config.getTimeBetweenConnectErrorMillis());
046        druidDataSource.setValidationQuery(config.getValidationQuery());
047        druidDataSource.setTestWhileIdle(config.isTestWhileIdle());
048        druidDataSource.setTestOnBorrow(config.isTestOnBorrow());
049        druidDataSource.setTestOnReturn(config.isTestOnReturn());
050        if (config.getMinimumIdle() != null) {
051            druidDataSource.setMinIdle(config.getMinimumIdle());
052        }
053
054        if (config.getConnectionInitSql() != null) {
055            druidDataSource.setConnectionInitSqls(Sets.newHashSet(config.getConnectionInitSql()));
056        }
057
058        try {
059            druidDataSource.setFilters("stat");
060        } catch (SQLException e) {
061            log.error("DruidDataSourceFactory is error", e);
062        }
063
064
065        return druidDataSource;
066    }
067}