简体   繁体   中英

JPA - CommunicationsException: Communications link failure at second connection

I have an application using JPA EclipseLInk 2.5.2 which contacts every minute a mysql to do things. The first thing that has to be done is to say it's alive to the DB. To do this I use a ScheuledExecutorService running a busioness object every minute. This object opens an closes DAOs each time.

On my dev environment (my computer), with Wamp64 bits and mysql configured by default, everything is OK. When I put on a preprod server (CentOS 7, mysql Ver 14.14 Distrib 5.7.16), the first loop is OK, but the next ones fail with this message when trying to execute a sql query with a DAO :

[EL Warning]: 2016-12-13 09:35:01.936--UnitOfWork(1778154389)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet successfully received from the server was 57 316 milliseconds ago.  The last packet sent successfully to the server was 4 milliseconds ago.
Error Code: 0
Call: SELECT id, lastDateAliveChargement, lastDateAliveDechargement FROM LastAlive
Query: ReportQuery(referenceClass=LastAlive sql="SELECT id, lastDateAliveChargement, lastDateAliveDechargement FROM LastAlive")

On preprod I used first a mariaDB used with the mariaDB jdbc driver. Then I switched to mysql with mysql jdbc driver, and I still got the problem. When I list the pending connections on the mysql they still appear with command Sleep until the wait_timeout is expired. I tried to configure mysql with these settings (my.cnf)

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
max_connections=100
port=3306
wait_timeout=3600   

On my computer (wamp, so windows) : [mysql] no-auto-rehash //fails to start with this param on the server [mysqld] port = 3306

Here are the params for JPA initialization :

persistenceMapInitiales.put("javax.persistence.jdbc.driver","com.mysql.cj.jdbc.Driver");            
persistenceMapInitiales.put("javax.persistence.jdbc.url","jdbc:mysql://MY_REMOTE_IP/myDB?characterEncoding=utf-8&useLegacyDatetimeCode=false&serverTimezone=UTC&autoReconnect=true&useSSL=false");
persistenceMapInitiales.put("javax.persistence.jdbc.user","toto");
persistenceMapInitiales.put("javax.persistence.jdbc.password","toto");
persistenceMapInitiales.put("eclipselink.ddl-generation","create-or-extend-tables");
persistenceMapInitiales.put("eclipselink.create-ddl-jdbc-file-name","createDDL_ddlGeneration.jdbc"); 
persistenceMapInitiales.put("eclipselink.drop-ddl-jdbc-file-name","dropDDL_ddlGeneration.jdbc"); 
persistenceMapInitiales.put("eclipselink.ddl.default-table-suffix","engine=InnoDB");
persistenceMapInitiales.put("eclipselink.ddl-generation.output-mode","both");

persistenceMapInitiales.put("eclipselink.connection-pool.default.initial","1" );
persistenceMapInitiales.put("eclipselink.connection-pool.default.min","64" );
persistenceMapInitiales.put("eclipselink.connection-pool.default.max","64" );  

The declaration of the scheduledExectorService :

public static void main(String[] args)
{
    final Integer CRON_PERIOD = 1; // every minute
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    scheduler.scheduleAtFixedRate(new MyWork(), 0, CRON_PERIOD, TimeUnit.MINUTES);
}

The Business class

public class MyWork() implements Runnable{

    private LastAliveDao lastAliveDao;
    //...

    public void run()
    {
        sayIsAlive();
        //...
    }

    private void sayIsAlive()
    {
        logger.info("upadet isAlive");
        try{
            lastAliveDao = new JpaLastAliveDao();
            lastAliveDao.sayChargementIsAlive();
        }catch(Exception e){
            logger.error("", e);
        }finally{
            try{
                lastAliveDao.close();
            }catch(Exception e)
            {
                logger.warn("Exception closing dao : ", e);
            }
            lastAliveDao = null;
        }
    }
}

The DAO code :

public class JpaLastAliveDao extends JpaDao<LastAlive, Integer> implements LastAliveDao {

@Override
public void sayChargementIsAlive() {
    List<LastAlive> alives = this.list();
    if(alives.size() == 0){
        LastAlive alive = new LastAlive();
        alive.setLastDateAliveChargement(Calendar.getInstance().getTime());
        this.persist(alive);
    }else{
        LastAlive alive = alives.get(0);
        alive.setLastDateAliveChargement(Calendar.getInstance().getTime());
        this.update(alive);
    }
}

And the JpaDAO code :

public abstract class JpaDao<T, PK extends Serializable>
    implements Dao<T, PK>{

    protected Class<T> entityClass;

    protected EntityManagerFactory emf;
    protected EntityManager em;

    @SuppressWarnings("unchecked")
    public JpaDao()
    {
        emf = JPAUtils.getInstance("facturator").getEmf();
        em = emf.createEntityManager();
        ParameterizedType genericSuperclass = (ParameterizedType) 
                getClass().getGenericSuperclass();
        this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
    }

    public T persist(T t) {
        this.em.getTransaction().begin();
        this.em.persist(t);
        this.em.getTransaction().commit();
        return t;
    }

    public T findById(PK id) {
        return this.em.find(entityClass, id);
    }

    public T update(T t) {
        this.em.getTransaction().begin();
        T entityPersist = this.em.merge(t);
        this.em.getTransaction().commit();
        return entityPersist;
    }

    @SuppressWarnings("unchecked")
    public List<T> list()
    {
        return this.em.createQuery("SELECT t FROM "+entityClass.getName()+" t ").getResultList();
    }

    public void delete(T t) {
        this.em.getTransaction().begin();
        this.em.remove(t);
        this.em.getTransaction().commit();
    }

    public void close(){
        em.close();
    }

}

OK I've found the reason. The DB server and the program server were configured on 2 differents submask network : 255.255.255.0 for one, and 255.255.255.255 for another one.

I found it with a SocketException that was not displayed in the stack with initial log settings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM