通过GAE Flex中的连接池连接Cloud SQL的最佳方式

时间:2018-02-26 05:57:52

标签: java sql google-app-engine google-cloud-platform google-cloud-sql

我正在将Hibernate v5与GAE Flexible环境和Cloud SQL结合使用。

一切正常,但是当一个实例被唤醒或者在一些寒冷的时间之后(没有请求服务),连接到数据库需要很长时间(最多8s),而查询的执行只需要ms。它还会一次又一次地创建 serviceRegistry

任何人都可以建议什么是与Cloud SQL连接的最佳方法,以避免更高的延迟获取连接。

PS:我使用cp30进行连接池。

来自应用引擎的日志:

enter image description here

enter image description here HibernateUtil配置:

        props.put("hibernate.hbm2ddl.auto", "validate");
        props.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
        props.put("hibernate.generate_statistics", "true");
        props.put("hibernate.cache.use_query_cache", "true");
        props.put("hibernate.transaction.coordinator_class", "org.hibernate.transaction.JDBCTransactionFactory");
        props.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory");
        props.put("hibernate.cache.use_second_level_cache", "true");

        props.put("connection.provider_class", "org.hibernate.connection.C3P0ConnectionProvider");
        props.put("hibernate.c3p0.min_size", "40");
        props.put("hibernate.c3p0.max_size", "250");
        props.put("hibernate.c3p0.acquire_increment", "1");
        props.put("hibernate.c3p0.testConnectionOnCheckin", "true");
        props.put("hibernate.c3p0.idle_test_period", "300");
        props.put("hibernate.c3p0.maxIdleTimeExcessConnections", "240");
        props.put("hibernate.c3p0.preferredTestQuery", "SELECT 1");
         ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        System.out.println("Hibernate Java Config serviceRegistry created");

        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        return sessionFactory;

2 个答案:

答案 0 :(得分:2)

除非您使用manual scaling,否则您的实例通常会被终止并重新启动。实例必须在它们启动时重新加载所有库和配置,因此它的预期行为需要更长的时间。

您的用例有两个简单的选项:

1)使用Compute Engine instance,它允许您加载代码,库和配置,它是一个专用的VM,它将继续为您的请求提供服务,并且不会“缩小”(终止)。这绝对是最安全的方法。

2)使用manual scaling扩展App Engine Flex应用。这几乎和第一个选项一样有效,但如果实例不健康,实例仍然可以重新启动。在这种情况下,如果发生某些事情,请确保您有health check设置来修复您的实例。这将使他们保持活力并尽可能地工作。

答案 1 :(得分:-2)

我并不完全确定你的意思"一个实例被唤醒"作为一个实例是活着还是死了。空闲时的作用取决于你的scaling settings in the app.yaml,它可能会死亡或保持空转状态。

我认为sessionFactory的创建是导致延迟的原因。由于Session工厂封装会话对象,连接,Hibernate属性缓存和映射,这是一个代价高昂的过程。

我很想知道如果你重复使用sessionFactory会发生什么(根据here无耻地窃取的例子):

.widest{
  margin-left: calc( (100vw - 960px) / -2 );
}

由于您没有提供完整的代码,因此您必须根据自己的情况调整此示例。

相关问题