feat 连接池修改为德罗伊连接池
parent
c3548ba95b
commit
5e68e0dd94
|
@ -0,0 +1,75 @@
|
||||||
|
package com.muyu.source.client.source;
|
||||||
|
|
||||||
|
import com.alibaba.druid.pool.DruidDataSource;
|
||||||
|
import com.alibaba.druid.pool.DruidPooledConnection;
|
||||||
|
import com.muyu.source.domain.Kvt;
|
||||||
|
import lombok.extern.log4j.Log4j2;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.HashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据源配置连接池 DataSourceConfig
|
||||||
|
*
|
||||||
|
* @author Yangle
|
||||||
|
* Date 2024/5/14 21:59
|
||||||
|
*/
|
||||||
|
@Log4j2
|
||||||
|
@Component
|
||||||
|
public class DataSourceConfig {
|
||||||
|
private static HashMap<Long, DruidDataSource> hashMap=new HashMap<>();
|
||||||
|
|
||||||
|
//创建初始化连接池
|
||||||
|
public static void init(Kvt kvt){
|
||||||
|
// 创建连接池
|
||||||
|
DruidDataSource dataSource = new DruidDataSource();
|
||||||
|
// 设置连接池属性
|
||||||
|
dataSource.setUrl("jdbc:mysql://"+kvt.getHost()+":"+kvt.getPort()+"/"+kvt.getDatabaseName()+"?"+kvt.getConnectionParam());
|
||||||
|
// 设置连接池用户名
|
||||||
|
dataSource.setUsername(kvt.getUsername());
|
||||||
|
// 设置连接池密码
|
||||||
|
dataSource.setPassword(kvt.getPassword());
|
||||||
|
// 设置连接池初始化连接数量
|
||||||
|
dataSource.setInitialSize(Math.toIntExact(kvt.getInitNum()));
|
||||||
|
// 设置连接池最大连接数量
|
||||||
|
dataSource.setMaxActive(Math.toIntExact(kvt.getMaxNum()));
|
||||||
|
// 设置连接池最大等待时间
|
||||||
|
dataSource.setMaxWait(kvt.getMaxWaitTime());
|
||||||
|
// 设置连接池最小连接数量
|
||||||
|
dataSource.setMinIdle(Math.toIntExact(kvt.getInitNum()));
|
||||||
|
//设置连接池的驱动
|
||||||
|
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
|
||||||
|
try{
|
||||||
|
// 初始化连接池
|
||||||
|
dataSource.init();
|
||||||
|
}catch (SQLException e){
|
||||||
|
throw new RuntimeException("初始化失败",e);
|
||||||
|
}
|
||||||
|
hashMap.put(kvt.getId(),dataSource);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//获取连接
|
||||||
|
public static Connection getConnection(Long key){
|
||||||
|
DruidDataSource dataSource = hashMap.get(key);
|
||||||
|
try {
|
||||||
|
DruidPooledConnection connection = dataSource.getConnection();
|
||||||
|
return connection;
|
||||||
|
} catch (SQLException e) {
|
||||||
|
throw new RuntimeException("获取连接失败",e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//归还连接
|
||||||
|
public static void close(Connection connection){
|
||||||
|
if (connection!=null){
|
||||||
|
try {
|
||||||
|
connection.close();
|
||||||
|
} catch (SQLException e) {
|
||||||
|
throw new RuntimeException("归还连接失败",e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue