8
respostas

max_size do c3p0 não esta sendo obedecido

Ola, Estou utilizando o c3p0 para controlar as conexões em um projeto com JPA, sem Spring, mas o limite máximo de conexões não esta funcionando nem de perto. Limitei para no máximo 5 mas depois de algumas horas no ar, com acessos constantes, o banco está com centenas de conexões abertas. Tentei inclusive fechar manualmente após cada transação, mas o problema continuou. Já esgotei tdo que consegui pensar e pesquisar. Alguma ideia do que pode estar acontecendo?

8 respostas

Posta a configuração do c3p0, por favor

Opa, segue meu persistence:

<persistence-unit name="BBR"
    transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    <class>br.com.bb.uni.painelAnalista.modelos.Analista</class>
    <class>br.com.bb.uni.painelAnalista.modelos.Ocorrencia</class>
    <class>br.com.bb.uni.painelAnalista.modelos.Parecer</class>
    <class>br.com.bb.uni.painelAnalista.modelos.TextoConducao</class>

    <properties>
        <property name="javax.persistence.jdbc.driver"
            value="com.ibm.db2.jcc.DB2Driver" />
        <property name="javax.persistence.jdbc.url"
            value="" />
        <property name="javax.persistence.jdbc.user"
            value="" />
        <property name="javax.persistence.jdbc.password"
            value="" />

        <property name="hibernate.dialect"
            value="org.hibernate.dialect.DB2Dialect" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="true" />
        <property name="hibernate.hbm2ddl.auto" value="none" />

        <property name="hibernate.c3p0.min_size" value="1"/>
        <property name="hibernate.c3p0.max_size" value="3"/>
        <property name="hibernate.c3p0.timeout" value="60"/>
        <property name="hibernate.c3p0.max_statements" value="0"/>
        <property name="hibernate.c3p0.idle_test_period" value="120"/>
    </properties>


</persistence-unit>

<persistence-unit name="impessoal"
    transaction-type="RESOURCE_LOCAL">

    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    <class>br.com.bb.uni.painelAnalista.modelos.Analista</class>
    <class>br.com.bb.uni.painelAnalista.modelos.Ocorrencia</class>
    <class>br.com.bb.uni.painelAnalista.modelos.Parecer</class>
    <class>br.com.bb.uni.painelAnalista.modelos.TextoConducao</class>

    <properties>
        <property name="javax.persistence.jdbc.driver"
            value="com.ibm.db2.jcc.DB2Driver" />
        <property name="javax.persistence.jdbc.url"
            value="" />
        <property name="javax.persistence.jdbc.user"
            value="" />
        <property name="javax.persistence.jdbc.password"
            value="" />

        <property name="hibernate.dialect"
            value="org.hibernate.dialect.DB2Dialect" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="true" />
        <property name="hibernate.hbm2ddl.auto" value="none" />

        <property name="hibernate.c3p0.min_size" value="1"/>
        <property name="hibernate.c3p0.max_size" value="3"/>
        <property name="hibernate.c3p0.timeout" value="60"/>
        <property name="hibernate.c3p0.max_statements" value="0"/>
        <property name="hibernate.c3p0.idle_test_period" value="120"/>

    </properties>

</persistence-unit>

Vou colocar mais alguns códigos que imagino poder contextualizar melhor:

Minha classe de Conexão:

public class Conexao {

public EntityManager pegaConexao(String provider) {
    return Persistence.createEntityManagerFactory(provider).createEntityManager();
}

public EntityManager pegaConexaoBbr() {
    return Persistence.createEntityManagerFactory("BBR").createEntityManager();
}

public EntityManager pegaConexaoImpessoal() {
    return Persistence.createEntityManagerFactory("impessoal").createEntityManager();
}

}

A classe DAO que usa essa conexão:

public class PainelDao {

Conexao conexao = new Conexao();

EntityManager bbr = conexao.pegaConexaoBbr();
EntityManager impessoal = conexao.pegaConexaoImpessoal();


public List<Object[]> buscaOcorrenciasPareceresValidacoes(String chave) {

    try {

        bbr.getTransaction().begin();

        String busca = "select o, c, p, t, m from Ocorrencia o join Conducao c"
                + " on o.id.ocorrencia = c.id.ocorrencia and o.id.reabertura = c.id.reabertura left join Parecer p"
                + " on o.id.ocorrencia = p.id.ocorrencia and o.id.reabertura = p.id.reabertura join TextoConducao t"
                + " on o.id.ocorrencia = t.id.ocorrencia and o.id.reabertura = t.id.reabertura join MeioResposta m"
                + " on o.id.ocorrencia = m.id.ocorrencia and o.id.reabertura = m.id.reabertura"
                + " where o.cd_conducao_pendente in (7, 13) and o.uor_responsavel = 77585 and c.tipo_conducao = 7"
                + " and c.usuario_conducao = :pUsuario and t.id.cdTipo in (9, 13)";

        TypedQuery<Object[]> query = bbr.createQuery(busca, Object[].class);

        query.setParameter("pUsuario", chave);

        List<Object[]> ocorrencias = query.getResultList();

        return ocorrencias;

    } catch (Exception e) {
        System.out.println(e.toString());
    }finally {

        System.out.println("conexao buscaOcorrenciasPareceresValidacoes aberta antes? " + bbr.isOpen());

        bbr.close();

        System.out.println("conexao buscaOcorrenciasPareceresValidacoes aberta depois? " + bbr.isOpen());
    }
    return null;
}

public List<PainelComentario> buscaComentarios(Set<Ocorrencia> ocorrenciasSolucao) {

    List<Integer> o = new ArrayList<>();
    List<Integer> r = new ArrayList<>();

    for (Ocorrencia ocorrencia : ocorrenciasSolucao) {
        o.add(ocorrencia.getId().getOcorrencia());
        r.add(ocorrencia.getId().getReabertura());
    }

    try {
        impessoal.getTransaction().begin();

        String busca = "select c from PainelComentario c"
                + " where c.id.ocorrencia in :pOcorrencias and c.id.reabertura in :pReabertura";

        TypedQuery<PainelComentario> query = impessoal.createQuery(busca, PainelComentario.class);

        query.setParameter("pOcorrencias", o);
        query.setParameter("pReabertura", r);

        List<PainelComentario> ocorrencias = query.getResultList();


        return ocorrencias;

    }catch (Exception e) {
        System.out.println(e.toString());
    } finally {
        System.out.println("conexao buscaComentarios aberta antes? " + impessoal.isOpen());

        impessoal.close();

        System.out.println("conexao buscaComentarios aberta depois? " + impessoal.isOpen());
    }
    return null;
}

public void atualizaComentario(Integer ocorrencia, Integer reabertura, String comentario) {

    impessoal.getTransaction().begin();

    Pk_ocorrencia pk = new Pk_ocorrencia();
    pk.setOcorrencia(ocorrencia);
    pk.setReabertura(reabertura);

    PainelComentario c = impessoal.find(PainelComentario.class, pk);

    if (c == null) {
        c = new PainelComentario();
        c.setId(pk);
        c.setComentario(comentario);
        impessoal.persist(c);
        impessoal.getTransaction().commit();
    } else {
        c.setComentario(comentario);
        impessoal.getTransaction().commit();
    }

    System.out.println("conexao atualizaComentario aberta antese? " + impessoal.isOpen());

    impessoal.close();

    System.out.println("conexao atualizaComentario aberta depois? " + impessoal.isOpen());
}

public void atualizaCor(Integer ocorrencia, Integer reabertura, String cor) {

    impessoal.getTransaction().begin();

    Pk_ocorrencia pk = new Pk_ocorrencia();
    pk.setOcorrencia(ocorrencia);
    pk.setReabertura(reabertura);

    PainelComentario c = impessoal.find(PainelComentario.class, pk);

    if (c == null) {
        c = new PainelComentario();
        c.setId(pk);
        c.setCor(cor);
        impessoal.persist(c);
        impessoal.getTransaction().commit();
    } else {
        c.setCor(cor);
        impessoal.getTransaction().commit();
    }

    System.out.println("conexao atualizaCor aberta antes? " + impessoal.isOpen());

    impessoal.close();

    System.out.println("conexao atualizaCor aberta depois? " + impessoal.isOpen());

}

continuação:

public List<Object[]> buscaEncerradas(String chave, LocalDateTime inicio, LocalDateTime fim) {

    bbr.getTransaction().begin();

    String busca = "select o, p from Ocorrencia o join Conducao c"
            + " on o.id.ocorrencia = c.id.ocorrencia and o.id.reabertura = c.id.reabertura left join Parecer p"
            + " on o.id.ocorrencia = p.id.ocorrencia and o.id.reabertura = p.id.reabertura"
            + " where o.cd_conducao_pendente in (0, 10) and o.uor_responsavel = 77585 and c.tipo_conducao = 7"
            + " and c.usuario_conducao = :pUsuario and c.dt_conducao between :pInicio and :pFim";

    TypedQuery<Object[]> query = bbr.createQuery(busca, Object[].class);

    query.setParameter("pUsuario", chave);
    query.setParameter("pInicio", inicio);
    query.setParameter("pFim", fim);

    List<Object[]> rl = query.getResultList();

    System.out.println("conexao buscaEncerradas aberta antes ? " + bbr.isOpen());

    bbr.close();

    System.out.println("conexao buscaEncerradas aberta depois? " + bbr.isOpen());

    return rl;
}

Quando eu executo o comando que efetua a busca, dispara uma exception. Eu tentei tdo que eu sabia pra resolve-la, mas não consegui, mas como a busca devolve o que foi solicitado, imaginei que não teria problema, agora estou com medo de que isso pode estar voltando para me assombrar.

ERROR: Could not fetch the SequenceInformation from the database
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=SYSCAT.SEQUENCES, DRIVER=4.25.13
    at com.ibm.db2.jcc.am.b6.a(b6.java:810)
    at com.ibm.db2.jcc.am.b6.a(b6.java:66)
    at com.ibm.db2.jcc.am.b6.a(b6.java:140)
    at com.ibm.db2.jcc.am.k3.c(k3.java:2824)
    at com.ibm.db2.jcc.am.k3.d(k3.java:2808)
    at com.ibm.db2.jcc.am.k3.a(k3.java:2234)
    at com.ibm.db2.jcc.t4.ab.i(ab.java:206)
    at com.ibm.db2.jcc.t4.ab.b(ab.java:96)
    at com.ibm.db2.jcc.t4.p.a(p.java:32)
    at com.ibm.db2.jcc.t4.av.i(av.java:150)
    at com.ibm.db2.jcc.am.k3.al(k3.java:2203)
    at com.ibm.db2.jcc.am.k3.a(k3.java:3330)
    at com.ibm.db2.jcc.am.k3.a(k3.java:737)
    at com.ibm.db2.jcc.am.k3.executeQuery(k3.java:716)
    at com.mchange.v2.c3p0.impl.NewProxyStatement.executeQuery(NewProxyStatement.java:220)
    at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.extractMetadata(SequenceInformationExtractorLegacyImpl.java:42)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.sequenceInformationList(JdbcEnvironmentImpl.java:403)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.<init>(JdbcEnvironmentImpl.java:268)

Também reparei que parece que ele recria o pool toda vez que mando fazer a pesquisa. Toda vez que o comando de trazer os dados é executado, o console mostra isso:

ago 16, 2019 9:13:22 AM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation INFO: HHH000204: Processing PersistenceUnitInfo [name: BBR] ago 16, 2019 9:13:23 AM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {5.4.3.Final} ago 16, 2019 9:13:23 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final} ago 16, 2019 9:13:24 AM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure INFO: HHH010002: C3P0 using driver: com.ibm.db2.jcc.DB2Driver at URL: jdbc:db2://GWDB2.BB.COM.BR:50100/BDB2P04:currentSchema=DB2BBR; ago 16, 2019 9:13:24 AM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure INFO: HHH10001001: Connection properties: {user=DB2I1024, password=} ago 16, 2019 9:13:24 AM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure INFO: HHH10001003: Autocommit mode: false ago 16, 2019 9:13:24 AM com.mchange.v2.log.MLog INFORMAÇÕES: MLog clients using java 1.4+ standard logging. ago 16, 2019 9:13:24 AM com.mchange.v2.c3p0.C3P0Registry INFORMAÇÕES: Initializing c3p0-0.9.5.3 [built 27-January-2019 00:11:37 -0800; debug? true; trace: 10] ago 16, 2019 9:13:24 AM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure INFO: HHH10001007: JDBC isolation level: ago 16, 2019 9:13:24 AM com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource INFORMAÇÕES: Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@b620137a [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@c0f7c544 [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, contextClassLoaderSource -> caller, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceSynchronousCheckins -> false, identityToken -> 1bqsqooa416tq5v81d7ue0f|18508b92, idleConnectionTestPeriod -> 120, initialPoolSize -> 1, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 60, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 3, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 1, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@68f7951f [ description -> null, driverClass -> null, factoryClassLocation -> null, forceUseNamedDriverClass -> false, identityToken -> 1bqsqooa416tq5v81d7ue0f|4fe0a0b, jdbcUrl -> jdbc:db2://GWDB2.BB.COM.BR:50100/BDB2P04:currentSchema=DB2BBR;, properties -> {user=**, password=**} ], preferredTestQuery -> null, privilegeSpawnedThreads -> false, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, extensions -> {}, factoryClassLocation -> null, identityToken -> 1bqsqooa416tq5v81d7ue0f|7683f836, numHelperThreads -> 3 ] ago 16, 2019 9:13:25 AM org.hibernate.dialect.Dialect INFO: HHH000400: Using dialect: org.hibernate.dialect.DB2Dialect ago 16, 2019 9:13:26 AM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl sequenceInformationList

A pool não deveria ser criada apenas uma vez? Na primeira execução?