Advertisement
Guest User

Untitled

a guest
Jun 3rd, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 3.90 KB | None | 0 0
  1. public class DatabaseConnection {
  2.     private static final Logger log = LoggerFactory.getErrLogger();
  3.     private static final HashMap<Integer, ConWrapper> connections =
  4.             new HashMap();
  5.     private static String dbDriver, dbUrl, dbUser, dbPass;
  6.     private static boolean propsInited = false;
  7.     private static long connectionTimeOut = 5 * 60 * 1000; // 5 minutes
  8.  
  9.     private DatabaseConnection() {}
  10.  
  11.     public static Connection getConnection() {
  12.         Thread cThread = Thread.currentThread();
  13.         int threadID = (int) cThread.getId();
  14.         ConWrapper ret = connections.get(threadID);
  15.  
  16.         if (ret == null) {
  17.             Connection retCon = connectToDB();
  18.             ret = new ConWrapper(retCon);
  19.             ret.id = threadID;
  20.             connections.put(threadID, ret);
  21.             log.info("[Database] Thread [" + threadID + "] has created a new Database Connection.");
  22.         }
  23.  
  24.         return ret.getConnection();
  25.     }
  26.  
  27.     private static long getWaitTimeout(Connection con) {
  28.         Statement stmt = null;
  29.         ResultSet rs = null;
  30.         try {
  31.             stmt = con.createStatement();
  32.             rs = stmt.executeQuery("SHOW VARIABLES LIKE 'wait_timeout'");
  33.             if (rs.next()) {
  34.                 return Math.max(1000, rs.getInt(2) * 1000 - 1000);
  35.             } else {
  36.                 return -1;
  37.             }
  38.         } catch (SQLException ex) {
  39.             return -1;
  40.         } finally {
  41.             if (stmt != null) {
  42.                 try {
  43.                     stmt.close();
  44.                 } catch (SQLException ex) {
  45.                 } finally {
  46.                     if (rs != null) {
  47.                         try {
  48.                             rs.close();
  49.                         } catch (SQLException ex1) {}
  50.                     }
  51.                 }
  52.             }
  53.         }
  54.     }
  55.  
  56.     private static Connection connectToDB() {
  57.         if (!propsInited) {
  58.             PropertyReader dbReader;
  59.  
  60.             try {
  61.                 dbReader = PropertyReader.load("db.cfg");
  62.             } catch (IOException ex) {
  63.                 throw new DatabaseException(ex);
  64.             }
  65.  
  66.             dbDriver = dbReader.getProperty("driver");
  67.             dbUrl = dbReader.getProperty("url");
  68.             dbUser = dbReader.getProperty("user");
  69.             dbPass = dbReader.getProperty("password");
  70.             try {
  71.                 connectionTimeOut = Long.parseLong(dbReader.getProperty("timeout"));
  72.             } catch (Exception e) {
  73.                 log.warn("[Database] Cannot read Connection Timeout Information, using default: " + connectionTimeOut);
  74.             }
  75.         }
  76.  
  77.         try {
  78.             Class.forName(dbDriver);    // touch the MySQL driver
  79.         } catch (ClassNotFoundException e) {
  80.             throw new DatabaseException(e);
  81.         }
  82.  
  83.         try {
  84.             Connection con = DriverManager.getConnection(dbUrl, dbUser, dbPass);
  85.             if (!propsInited) {
  86.                 long timeout = getWaitTimeout(con);
  87.                 if (timeout == -1) {
  88.                     log.error("[Database] Failed to read Wait_Timeout, using " + connectionTimeOut + " instead.");
  89.                 } else {
  90.                     connectionTimeOut = timeout;
  91.                     log.info("[Database] Timeout is " + connectionTimeOut + " milliseconds.");
  92.                 }
  93.                 propsInited = true;
  94.             }
  95.             return con;
  96.         } catch (SQLException e) {
  97.             throw new DatabaseException(e);
  98.         }
  99.     }
  100.  
  101.     static class ConWrapper {
  102.         private long lastAccessTime = 0;
  103.         private Connection connection;
  104.         private int id;
  105.  
  106.         public ConWrapper(Connection con) {
  107.             this.connection = con;
  108.         }
  109.  
  110.         public Connection getConnection() {
  111.             if (expiredConnection()) {
  112.                 log.info("[Database] Connection #" + id + " has gone stale. Reconnecting..");
  113.                 try { // Assume that the connection is stale
  114.                     connection.close();
  115.                 } catch (Throwable err) {
  116.                     // Who cares
  117.                 }
  118.                 this.connection = connectToDB();
  119.             }
  120.  
  121.             lastAccessTime = System.currentTimeMillis(); // Record Access
  122.             return this.connection;
  123.         }
  124.  
  125.         /**
  126.          * Returns whether this connection has expired
  127.          * @return
  128.          */
  129.         public boolean expiredConnection() {
  130.             if (lastAccessTime == 0) {
  131.                 return false;
  132.             }
  133.             try {
  134.                 return System.currentTimeMillis() - lastAccessTime >= connectionTimeOut || connection.isClosed();
  135.             } catch (Throwable ex) {
  136.                 return true;
  137.             }
  138.         }
  139.     }
  140.  
  141.     public static void closeAll() throws SQLException {
  142.         for (ConWrapper con : connections.values()) {
  143.             con.connection.close();
  144.         }
  145.         connections.clear();
  146.     }
  147. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement