Quantcast
Channel: GUJ - Tópicos com a tag java
Viewing all articles
Browse latest Browse all 17410

Ajuda com Singleton

$
0
0

@picklesdog70 escreveu:

Estou utilizando o seguinte singleton para conexão ao banco de dados MySQL

public class DbConnectionFactory {
	
	private static Connection connection;
	private static Properties database;

	private DbConnectionFactory(){
		
	}
	
	static{
		try{
			InputStream is = ServletController.class.getResourceAsStream("/database.properties");
			database = new Properties();
			database.load(is);
		}catch (Exception e) {
			throw new RuntimeException("Arquivo de propriedades responsável pela conexão com o banco de dados não foi encontrado");
		}		
	}
	
	public static Connection getInstance() throws Exception{
		try{
			if(connection == null){
				Class.forName("com.mysql.jdbc.Driver");
				connection = DriverManager.getConnection("jdbc:mysql://" + database.getProperty("server") + ":"+ database.getProperty("port") +"/"+ database.getProperty("database") +"?serverTimezone=GMT-03:00",database.getProperty("user"),database.getProperty("password"));
				connection.setAutoCommit(false);
			}
		}catch (Exception e) {
			throw new Exception("Não foi possível conectar com o banco de dados. Erro: " + e.getMessage());
		}
		
		return connection;
	}
	
}

Para iniciar a transação, faço o seguinte.......

		try{
			DbConnectionFactory.getInstance();
			process();
			DbConnectionFactory.getInstance().commit();
		}catch (Exception e) {
			DbConnectionFactory.getInstance().rollback();
			throw new ActionException(e.getMessage());
		}

E nos DAOs faço:

PreparedStatement stmt = DbConnectionFactory.getInstance().prepareStatement("INSERT INTO .....

No meu computador....que o timeout do MySQL é gigante.... funciona na boa..... no servidor....o timeout é de 60 segundos......... se ocorrer o timeout recebo o erro abaixo e só consigo reconectar se reiniciar a aplicação no Tomcat.

javax.servlet.ServletException: Communications link failure The last packet successfully received from the server was 255.066 milliseconds ago. The last packet sent successfully to the server was 24 milliseconds ago.

Mensagens: 5

Participantes: 2

Ler tópico completo


Viewing all articles
Browse latest Browse all 17410

Latest Images

Trending Articles

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>