Pool de connexion ou singleton
Bonsoir,
J'ai une petite question à propos de connexion a une base de données.
J'ai développé un pattern singleton pour me connecter à ma base, c'est pratique puisque du coup je ne ferme jamais ma connexion et plusieurs utlisateurs peuvent du coup l'utiliser, voici mon code:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| public static DBConnection getInstance() throws Exception {
if (DBConnection.dbconnection == null) {
//String path = "blabla";
String path = "blabla";
props.load(new FileInputStream(path));
//mettre en place le fichier de log la première fois
PropertyConfigurator.configure(props.getProperty("pathLog4j"));
setLog4j(Logger.getLogger("DBConnection.class"));
if(Logger.getLogger("DBConnection.class") == null)
System.out.println("La mise en place du système de log n'a pas fonctionné ");
else
log4j.log(Level.INFO,"Le système de log est mis en place: "+ getLog4j().getName());
log4j.log(Level.INFO, "pathLog4j: "+props.getProperty("pathLog4j"));
DBConnection.dbconnection = new DBConnection();
log4j.log(Level.INFO, "DBConnection.dbconnection = new DBConnection();");
}
return DBConnection.dbconnection;
}
public Connection getConnection() throws Exception {
if (DBConnection.dbconnection == null)
throw new Exception("Singleton non initialisé");
if (DBConnection.conn != null && !DBConnection.conn.isClosed())
{
return DBConnection.conn;
}
else
log4j.log(Level.INFO, "Connection == null");
try {
DBConnection.conn = getConnection3();
} catch (Exception ex) {
log4j.log(Level.FATAL, "Erreur lors du chargement du dataSource");
ex.printStackTrace();
throw new Exception("Erreur lors du chargement du dataSource");
}
return conn;
}
private static Connection getConnection3() throws Exception {
if (DBConnection.conn != null && !DBConnection.conn.isClosed())
{
return DBConnection.conn;
}
user = props.getProperty("user");
password = props.getProperty("password");
host = props.getProperty("host");
port = props.getProperty("port");
dbname = props.getProperty("dbname");
try {
String url = "jdbc:mysql://" + host +":"+port+ "/" + dbname;
log4j.log(Level.INFO, "url: "+ "jdbc:mysql://" + host +":"+port+ "/" + dbname);
Class.forName("com.mysql.jdbc.Driver").newInstance();
DBConnection.conn = DriverManager.getConnection(url, user, password);
log4j.log(Level.INFO, "Connection DB réussie");
} catch (Exception e) {
log4j.log(Level.FATAL, "Echec de la connection DB" + e);
}
return DBConnection.conn;
} |
Et j'ai lu par ci par là que ce n'était pas bien qu'il fallait passer par un pool de connexion, je ne comprend pas pourquoi c'est mieux. Ou est l'avantage? et surtout est ce ma méthode est dangereuse?
Merci pour votre aide précieuse,