如何解决Google CloudSQL 8小时超时? [英] How to solve Google CloudSQL 8 hours timeout?

查看:79
本文介绍了如何解决Google CloudSQL 8小时超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有Google Cloud SQL的应用程序.我使用的是Hibernate 4.2.0.Final,我注意到在闲置8小时后,我的连接已关闭.我一直在Internet上搜索,但找不到有效解决此问题的方法.这些项目中总结了我找到的所有信息:

I'm working in an app with Google Cloud SQL. I'm using Hibernate 4.2.0.Final and I've noticed that after 8 hours of inactivity my connection is closed. I've been searching on the Internet and I couldn't find anything effective to solve this issue. All the information I've found is summarized in these items:

  • 使用连接池,我应该在其中指定更高的超时时间.我已经尝试过使用c3p0和DBCP 2.1.1库,但是它们都不能解决问题.
  • 在进行某些查询之前先打开一个连接,然后再关闭它.问题是我想使用EntityManager以便对实体使用查询.

这就是我对DBCP 2.1.1所做的操作( http://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2/2.1.1 ).问题是当我尝试在 PersistenceService 中使用 findAll 时,Goggle App Engine日志会显示 ExceptionInInitializerError .日志还显示我的 DataSource (请参见下文)无法转换为 String .我不明白为什么.

Here it's what I've done with DBCP 2.1.1 (http://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2/2.1.1). The problem is that Goggle App Engine logs show an ExceptionInInitializerError when I try to use findAll in my PersistenceService. The logs also show that my DataSource (see below) cannot be cast to String. I don't understand why.

这是我现在正在使用的 PersistenceService

This is the PersistenceService I'm using right now

package co.peewah.ems.utils;

import com.google.appengine.api.utils.SystemProperty;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.AbstractMap.SimpleEntry;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.hibernate.cfg.AvailableSettings;


/**
 *
 * @author Muacito
 */
public class PersistenceService
{
    private static final EntityManagerFactory EMF = createEntityManagerFactory();

    private static EntityManager entityManager = EMF.createEntityManager();

    private static EntityManagerFactory createEntityManagerFactory()
    {
        //String mode = "";
        /*
        if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Development)
        {
            mode = "dev.";
        }
        */

        Map<String, Object> properties = new HashMap<>();

        //Properties properties = new Properties();

        //properties.put("javax.persistence.jdbc.driver", System.getProperty("persistence." + mode + "db.driver"));
        //properties.put("javax.persistence.jdbc.url", System.getProperty("persistence." + mode + "db.url"));
        //properties.put("javax.persistence.jdbc.user", System.getProperty("persistence." + mode + "db.user"));
        //properties.put("javax.persistence.jdbc.password", System.getProperty("persistence." + mode + "db.password"));
        try
        {
            properties.put(AvailableSettings.DATASOURCE, DataSource.getInstance());
        } catch (IOException | SQLException | PropertyVetoException e)
        {
             e.printStackTrace();
        }


        System.out.println("----------------------------");
        System.out.println("----------------------------");
        System.out.println(properties);
        System.out.println("----------------------------");
        System.out.println("----------------------------");

        return Persistence.createEntityManagerFactory("Demo", properties);
    }

    private static EntityManager getEntityManager()
    {
        if (!PersistenceService.entityManager.isOpen())
        {
            PersistenceService.entityManager = PersistenceService.EMF.createEntityManager();
        }

        return PersistenceService.entityManager;
    }

    public static <T> void create(T entity)
    {
        try
        {
            if (entity.getClass().getMethod("getId").invoke(entity) == null)
            {
                entity.getClass().getMethod("setId", String.class).invoke(entity,
                        UUID.randomUUID().toString().replace("-", ""));
            }

            if (entity.getClass().getMethod("getCreated").invoke(entity) == null)
            {
                entity.getClass().getMethod("setCreated", Date.class).invoke(entity,
                        GregorianCalendar.getInstance().getTime());
            }

            getEntityManager().getTransaction().begin();

            getEntityManager().persist(entity);

            getEntityManager().flush();

            getEntityManager().getTransaction().commit();

        } catch (Exception ex)
        {
            Logger.getLogger(PersistenceService.class.getName()).log(Level.SEVERE, null, ex);
            getEntityManager().getTransaction().rollback();
        }
    }

    public static <T> void edit(T entity)
    {
        try
        {
            if (entity.getClass().getMethod("getUpdated").invoke(entity) == null)
            {
                entity.getClass().getMethod("setUpdated", Date.class).invoke(entity,
                        GregorianCalendar.getInstance().getTime());
            }

            getEntityManager().getTransaction().begin();

            getEntityManager().merge(entity);

            getEntityManager().flush();

            getEntityManager().getTransaction().commit();
        } catch (Exception ex)
        {
            Logger.getLogger(PersistenceService.class.getName()).log(Level.SEVERE, null, ex);
            getEntityManager().getTransaction().rollback();
        }
    }

    public static <T> void remove(T entity)
    {
        try
        {
            getEntityManager().getTransaction().begin();

            getEntityManager().remove(entity);

            getEntityManager().flush();

            getEntityManager().getTransaction().commit();

        } catch (Exception ex)
        {
            Logger.getLogger(PersistenceService.class.getName()).log(Level.SEVERE, null, ex);
            getEntityManager().getTransaction().rollback();
        }
    }

    public static <T> List<T> filter(Class<T> entityClass, String query, SimpleEntry<String, Object>... parameters)
    {
        TypedQuery<T> typedQuery = getEntityManager().createQuery(query, entityClass);

        for (SimpleEntry<String, Object> param : parameters)
        {
            typedQuery.setParameter(param.getKey(), param.getValue());
        }

        return typedQuery.getResultList();
    }

    public static <T> T find(Class<T> entityClass, Object id)
    {
        T entity = getEntityManager().find(entityClass, id);

        return entity;
    }

    public static <T> List<T> findBy(Class<T> entityClass, String criteria, Object value)
    {
        String c = criteria.replaceFirst(criteria.charAt(0) + "", (criteria.charAt(0) + "").toLowerCase());

        TypedQuery<T> query = getEntityManager().createNamedQuery(entityClass.getSimpleName() + ".findBy" + criteria,
                entityClass);
        query.setParameter(c, value);

        return query.getResultList();
    }

    public static <T> List<T> findAll(Class<T> entityClass)
    {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));

        return getEntityManager().createQuery(cq).getResultList();
    }

    public static <T> List<T> findRange(Class<T> entityClass, int[] range)
    {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0] + 1);
        q.setFirstResult(range[0]);

        return q.getResultList();
    }

    public static <T> int count(Class<T> entityClass)
    {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        Query q = getEntityManager().createQuery(cq);

        return ((Long) q.getSingleResult()).intValue();
    }
}

这是我的 DataSource

package co.peewah.ems.utils;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbcp.BasicDataSource;

import com.google.appengine.api.utils.SystemProperty;

/**
 *
 * @author csacanam
 *
 */
public class DataSource
{

    private static DataSource datasource;
    private BasicDataSource ds;

    private DataSource() throws IOException, SQLException, PropertyVetoException
    {
        ds = new BasicDataSource();


        String mode = "";

        if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Development)
        {
            mode = "dev.";
        }

        String user = System.getProperty("persistence." + mode + "db.user");
        String password = System.getProperty("persistence." + mode + "db.password");
        String address = System.getProperty("persistence." + mode + "db.url");
        String driver = System.getProperty("persistence." + mode + "db.driver");

        // Create and configure DBCP DataSource
        ds.setDriverClassName(driver);
        ds.setUrl(address);
        ds.setUsername(user);
        ds.setPassword(password);

        ds.setMinIdle(5);
        ds.setMaxIdle(20);

        ds.setMaxOpenPreparedStatements(180);
    }

    public static DataSource getInstance() throws IOException, SQLException, PropertyVetoException
    {
        if(datasource == null)
        {
            datasource = new DataSource();    
        }

        return datasource;
    }

    public Connection getConnection() throws SQLException
    {
        return this.ds.getConnection();
    }




}

推荐答案

在Vadim的答案上加点说明,在CloudSQL上,您可以通过云控制台的Edit实例设置标志.在Google上,您无法通过运行 SET GLOBAL wait_timeout = 60; 之类的方法来执行此操作,因为它不支持SUPER特权.

Adding a bit to the answer of Vadim, on CloudSQL you can set flags through the cloud console Edit instance. On Google you cannot do this by running something like SET GLOBAL wait_timeout=60; because it does not support SUPER privileges.

我花了一段时间才找到它,所以我认为将其添加到这里可能会帮助其他人.

It took me a while to find this one out, so I figured it might help some else to add it here.

这篇关于如何解决Google CloudSQL 8小时超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆