2015-02-14 2 views
1

У меня есть приложение, которое подключается к нескольким базам данных в одном экземпляре Google Cloud SQL. Основываясь на выпадающем выборе, приложение GAE будет выбирать записи из одной из 5 баз данных.«javax.persistence.PersistenceException: Ошибка связи», когда приложение GAE пытается подключиться к нескольким базам данных Google Cloud SQL

Проблема заключается в том, что при выборе первых 4 баз данных (без указания порядка в выпадающем списке) приложение GAE успешно соединяется с базой данных и может извлекать записи. Но когда я выбираю пятую базу данных из выпадающего списка, возникает ошибка. Трассировка ошибок и стека выглядит следующим образом. Это не ошибка с конкретной базой данных, так как ошибка не зависит от того, какая база была выбрана. Выбранная последняя или пятая база данных, несущественная из которых, всегда терпит неудачу с тем же сообщением об ошибке.

Любой совет будет очень благодарен.

InspectAPI.java:

public Element[] getComponentsList(@Named("province")String provinceName, User user) throws Exception { 

    if (user == null) { 
     throw new UnauthorizedException("API calls must be authenticated."); 
    } 

    if (!AuthorizationService.hasAnyOrRoles(user.getEmail(), AuthorizationService.ROLE_ALL_ROLES) 
       || !AuthorizationService.hasProvincieAccess(user.getEmail(), provinceName)) { 
       throw new UnauthorizedException("You are not authorized to invoke this API method."); 
      } 

    EntityManager em = null; 
    Element[] e = null; 
    try { 
     em = EMF.getFStore().createEntityManager(); 
     em.getTransaction().begin(); 

     e = (ElementRubrieken[]) em.createQuery("SELECT i FROM Element i").getResultList() 
       .toArray(new Element[0]); 

    } catch (NoResultException nre) { 
     // no result 
     if (e == null) { 
      return e; 
     } 
    } catch (Exception ex) { 
     log.log(Level.SEVERE, "Unable to get inspections.", ex); 
     throw new InternalServerErrorException("Unable to get inspections."); 
    } finally { 
     if (em != null) { 
      em.getTransaction().commit(); 
      em.close(); 
     } 
    } 

    return e; 
} 

EMF.java

public static EntityManagerFactory getFicheStore() { 
    if (emfFicheInstance == null) { 
     Map<String, String> properties = new HashMap<String, String>(); 
     if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) { 
      properties.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.GoogleDriver"); 
      properties.put("javax.persistence.jdbc.url", System.getProperty("cloudsql.prod.f.url")); 
      properties.put("javax.persistence.jdbc.user", System.getProperty("cloudsql.prod.f.user")); 
      properties.put("javax.persistence.jdbc.password", System.getProperty("cloudsql.prod.f.password")); 
      properties.put("javax.persistence.jdbc.db", System.getProperty("cloudsql.prod.f.db"));    
     } else { 
      properties.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); 
      properties.put("javax.persistence.jdbc.url", System.getProperty("cloudsql.dev.f.url")); 
      properties.put("javax.persistence.jdbc.user", System.getProperty("cloudsql.dev.f.user")); 
      properties.put("javax.persistence.jdbc.password", System.getProperty("cloudsql.dev.f.password")); 
      properties.put("javax.persistence.jdbc.db", System.getProperty("cloudsql.dev.f.db")); 

     } 

     emfFicheInstance = Persistence.createEntityManagerFactory(
      System.getProperty("com.myproject.services.emfFactory.persistenceUnitName"), 
      properties); 
    } 

    return emfFicheInstance; 
} 

ошибок и трассировки стека:

E 00:42:39.184 com.myproject.api.InspectAPI getComponentsList: Unable to get inspections. 
    javax.persistence.PersistenceException: Communications link failure 

    The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. 
    at org.datanucleus.api.jpa.NucleusJPAHelper.getJPAExceptionForNucleusException(NucleusJPAHelper.java:270) 
    at org.datanucleus.api.jpa.JPAQuery.getResultList(JPAQuery.java:202) 
    at com.myproject.api.InspectAPI.getComponentsList(InspectAPI.java:223) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:606) 
    at com.google.apphosting.runtime.security.shared.intercept.java.lang.reflect.Method_$1.run(Method_.java:179) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at com.google.apphosting.runtime.security.shared.intercept.java.lang.reflect.Method_.privilegedInvoke(Method_.java:176) 
    at com.google.apphosting.runtime.security.shared.intercept.java.lang.reflect.Method_.invoke_(Method_.java:137) 
    at com.google.apphosting.runtime.security.shared.intercept.java.lang.reflect.Method_.invoke(Method_.java:45) 
    at com.google.api.server.spi.SystemService.invokeServiceMethod(SystemService.java:359) 
    at com.google.api.server.spi.SystemServiceServlet.execute(SystemServiceServlet.java:160) 
    at com.google.api.server.spi.SystemServiceServlet.doPost(SystemServiceServlet.java:118) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) 
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166) 
    at com.google.apphosting.utils.servlet.ParseBlobUploadFilter.doFilter(ParseBlobUploadFilter.java:125) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.apphosting.runtime.jetty.SaveSessionFilter.doFilter(SaveSessionFilter.java:35) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.apphosting.utils.servlet.JdbcMySqlConnectionCleanupFilter.doFilter(JdbcMySqlConnectionCleanupFilter.java:60) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388) 
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) 
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) 
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) 
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418) 
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.handle(AppVersionHandlerMap.java:254) 
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) 
    at org.mortbay.jetty.Server.handle(Server.java:326) 
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) 
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923) 
    at com.google.apphosting.runtime.jetty.RpcRequestParser.parseAvailable(RpcRequestParser.java:76) 
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) 
    at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:146) 
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:484) 
    at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:438) 
    at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:445) 
    at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:220) 
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:309) 
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:301) 
    at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:442) 
    at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251) 
    at java.lang.Thread.run(Thread.java:724) 
    Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure 

    The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 
    at java.lang.reflect.Constructor.newInstance(Constructor.java:46) 
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) 
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1117) 
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:350) 
    at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2416) 
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2450) 
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2235) 
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:818) 
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 
    at java.lang.reflect.Constructor.newInstance(Constructor.java:46) 
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) 
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:404) 
    at com.mysql.jdbc.GoogleNonRegisteringDriver$JdbcWrapper.getInstance(GoogleNonRegisteringDriver.java:276) 
    at com.mysql.jdbc.GoogleNonRegisteringDriver.connect(GoogleNonRegisteringDriver.java:246) 
    at java.sql.DriverManager.getConnection(DriverManager.java:571) 
    at java.sql.DriverManager.getConnection(DriverManager.java:187) 
    at org.datanucleus.store.rdbms.datasource.dbcp.DriverManagerConnectionFactory.createConnection(DriverManagerConnectionFactory.java:78) 
    at org.datanucleus.store.rdbms.datasource.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582) 
    at org.datanucleus.store.rdbms.datasource.dbcp.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1158) 
    at org.datanucleus.store.rdbms.datasource.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:108) 
    at org.datanucleus.store.rdbms.ConnectionProviderPriorityList.getConnection(ConnectionProviderPriorityList.java:57) 
    at org.datanucleus.store.rdbms.ConnectionFactoryImpl$ManagedConnectionImpl.getConnection(ConnectionFactoryImpl.java:354) 
    at org.datanucleus.store.rdbms.ConnectionFactoryImpl$ManagedConnectionImpl.getXAResource(ConnectionFactoryImpl.java:314) 
    at org.datanucleus.store.connection.ConnectionManagerImpl.enlistResource(ConnectionManagerImpl.java:354) 
    at org.datanucleus.store.connection.ConnectionManagerImpl.allocateConnection(ConnectionManagerImpl.java:226) 
    at org.datanucleus.store.connection.AbstractConnectionFactory.getConnection(AbstractConnectionFactory.java:60) 
    at org.datanucleus.store.AbstractStoreManager.getConnection(AbstractStoreManager.java:432) 
    at org.datanucleus.store.AbstractStoreManager.getConnection(AbstractStoreManager.java:401) 
    at org.datanucleus.store.rdbms.query.JPQLQuery.performExecute(JPQLQuery.java:512) 
    at org.datanucleus.store.query.Query.executeQuery(Query.java:1789) 
    at org.datanucleus.store.query.Query.executeWithMap(Query.java:1693) 
    at org.datanucleus.api.jpa.JPAQuery.getResultList(JPAQuery.java:185) 
    <continued in next message> 
E 00:42:39.184 <continued from previous message> 
    at com.myproject.api.InspectAPI.getComponentsList(InspectAPI.java:223) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:45) 
    at com.google.api.server.spi.SystemService.invokeServiceMethod(SystemService.java:359) 
    at com.google.api.server.spi.SystemServiceServlet.execute(SystemServiceServlet.java:160) 
    at com.google.api.server.spi.SystemServiceServlet.doPost(SystemServiceServlet.java:118) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) 
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157) 
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388) 
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) 
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) 
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) 
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418) 
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) 
    at org.mortbay.jetty.Server.handle(Server.java:326) 
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) 
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923) 
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) 
    at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:438) 
    at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:445) 
    at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:220) 
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:309) 
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:301) 
    at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:442) 
    ... 1 more 
    Caused by: java.net.SocketException: Unable to open connection to the instance: myproject-tst:mysql 
    at com.mysql.jdbc.GoogleCloudSqlSocket.<init>(GoogleCloudSqlSocket.java:48) 
    at com.mysql.jdbc.GoogleCloudSqlSocketFactory.connect(GoogleCloudSqlSocketFactory.java:81) 
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300) 
    ... 64 more 
    Caused by: java.io.FileNotFoundException: /cloudsql/myproject-tst:mysql (No such file or directory) 
    at java.io.RandomAccessFile.open(Native Method) 
    at java.io.RandomAccessFile.<init>(RandomAccessFile.java:247) 
    at java.io.RandomAccessFile.<init>(RandomAccessFile.java:132) 
    at com.mysql.jdbc.GoogleCloudSqlSocket$RandomAccessFileHelper.getFile(GoogleCloudSqlSocket.java:249) 
    at com.mysql.jdbc.GoogleCloudSqlSocket.<init>(GoogleCloudSqlSocket.java:46) 
    ... 66 more 

ответ

0

Я вижу два posibble причину этой ошибки:

  1. Вы попадаете в пределы 12 параллельных соединений, описанных здесь [1]. По какой-то причине вы можете не закрывать соединения должным образом.

  2. Я не эксперт по JPA, но я думаю, вам нужно создать единый блок постоянства на базу данных, к которой хотите подключиться к [2].

[1] https://cloud.google.com/appengine/docs/java/cloud-sql/#Java_Managing_connections

[2] http://www.mastertheboss.com/jboss-frameworks/hibernate-jpa/jpa-configuration/how-to-use-multiple-database-in-persistencexml

+0

Привет Лайонел, Да я подозреваю, что предел 12 соединения также является источником проблемы. Пробовал создавать разные единицы измерения на каждую базу данных, но это не работает. Также попытался установить ограничения пула соединений, и он тоже не работал. У меня заканчиваются идеи – EthanS

+0

@ EthanS вы когда-нибудь находили исправление проблемы подключения? Я столкнулся с той же проблемой и не смог найти причину. Его взгляд на нас, как повторы, может быть единственным вариантом, но я надеюсь избежать этого. – dansomething

+0

@dansomething Как часто вы получаете ошибки 'javax.persistence.PersistenceException: Communications failure failure? Используете ли вы объединение пулов? Каковы средние активные подключения к вашему экземпляру Cloud SQL? – Layo

Смежные вопросы