package com.muyu.cloud.common.many.datasource.factory;

import com.alibaba.druid.pool.DruidDataSource;
import com.muyu.cloud.common.many.datasource.domain.model.DataSourceInfo;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * @Author: zi run
 * @Date 2024/9/20 14:52
 * @Description Druid工厂
 */
@Log4j2
@Component
public class DruidDataSourceFactory {

    /**
     * 根据传递的数据源信息测试数据库连接
     * @param dataSourceInfo 数据源实体类
     * @return Druid连接池数据源
     */
    public DruidDataSource create(DataSourceInfo dataSourceInfo) {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(dataSourceInfo.getUrl());
        druidDataSource.setUsername(dataSourceInfo.getUserName());
        druidDataSource.setPassword(dataSourceInfo.getPassword());
        druidDataSource.setBreakAfterAcquireFailure(true);
        druidDataSource.setConnectionErrorRetryAttempts(0);
        try {
            druidDataSource.getConnection(2000);
            log.info("{} -> 数据源连接成功", dataSourceInfo.getKey());
            return druidDataSource;
        } catch (SQLException e) {
            log.error("数据源 {} 连接失败,用户名：{}，密码 {}",dataSourceInfo.getUrl(),dataSourceInfo.getUserName(),dataSourceInfo.getPassword());
            return null;
        }
    }
}
