Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package see613.core.db;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.LinkedList;
- import java.util.Queue;
- import see613.core.log.ILog;
- public class MysqlConnectionPool implements IConnectionPool {
- private Queue<Connection> pool = new LinkedList<Connection>();
- private ILog log;
- private String address;
- private String login;
- private String pass;
- public int connectTimeout = 3;
- public Connection get() throws Exception {
- synchronized (pool) {
- Connection connect;
- while (true) {
- connect = pool.poll();
- if ( connect == null ) {
- break;
- }
- if ( isValid(connect) ) {
- return connect;
- }
- }
- }
- return create();
- }
- public void add(Connection connect) {
- synchronized (pool) {
- pool.add(connect);
- }
- }
- private Connection create() throws Exception {
- Connection connect = null;
- try {
- Class.forName("com.mysql.jdbc.Driver");
- connect = DriverManager.getConnection( "jdbc:mysql://"+ getAddress(), getLogin(), getPass() );
- getLog().notice("new mysql connection: "+ getAddress() );
- } catch (Exception e) {
- close(connect);
- connect = null;
- throw e;
- }
- return connect;
- }
- public void close(Connection connect) throws Exception {
- if (connect != null) {
- connect.close();
- }
- }
- private Boolean isValid(Connection connect) throws SQLException {
- try {
- return connect.isValid( connectTimeout );
- } catch (SQLException e) {
- throw e;
- }
- }
- public void setLog(ILog value) {
- log = value;
- }
- private ILog getLog() {
- if ( log == null ) {
- throw new NullPointerException("log is null");
- }
- return log;
- }
- public void setAddress(String value) {
- address = value;
- }
- private String getAddress() {
- if ( address == null ) {
- throw new NullPointerException("address is null");
- }
- return address;
- }
- public void setLogin(String value) {
- login = value;
- }
- private String getLogin() {
- if ( login == null ) {
- throw new NullPointerException("login is null");
- }
- return login;
- }
- public void setPass(String value) {
- pass = value;
- }
- private String getPass() {
- if ( pass == null ) {
- throw new NullPointerException("pass is null");
- }
- return pass;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement