【问题标题】:Cloud Endpoints with Cloud SQL sample code带有 Cloud SQL 的 Cloud Endpoints 示例代码
【发布时间】:2015-06-09 14:07:10
【问题描述】:

我希望使用 Cloud Endpoints 在 Google App Engine 上创建 API,但我看到的所有教程都是关于如何与 Cloud Datastore 交互的。不过,我希望使用 Cloud SQL。

有没有人提供 Cloud Endpoints 类示例代码(Java 语言)来显示如何连接到 Cloud SQL 并执行一些简单的 INSERTSELECT 语句?例如

INSERT message INTO messages
SELECT * FROM messages

【问题讨论】:

  • Cloud Endpoints 基本上完成了对 Java 对象进行序列化/反序列化的工作,无论您使用什么数据库(如果有),这都是一样的,因此同样的教程适用于 CloudSQL。
  • @tx802 那么我应该问如何创建一个可以写入 Cloud SQL 的 Java 对象?好困惑....
  • @tx802 也许这就是我需要的? developers.google.com/eclipse/docs/cloudsql-jpatools
  • 是的,如果您使用 CloudSQL,JPA 将完成这项工作。您还可以阅读有关将 JPA 与 Cloud SQL 结合使用的信息here

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


【解决方案1】:

以下是更新 Cloud SQL 的示例 Cloud Endpoint 类。该示例假定端点已通过身份验证

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.api.server.spi.ServiceException;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.Named;
import com.google.api.server.spi.response.ForbiddenException;
import com.google.api.server.spi.response.InternalServerErrorException;
import com.google.appengine.api.oauth.OAuthRequestException;
import com.google.appengine.api.users.User;

@Api(
    name = "myendpoint",
    version = "v1",
    clientIds = {"ddddd.apps.googleusercontent.com"},
    audiences = {"xxxx"}
)
public class CloudSqlEndpoint {

    private static final Logger log = Logger.getLogger(CloudSqlEndpoint.class.getName());

    private static final String INSERT_ORDER_SQL = "INSERT INTO order (amount, user, status, address) VALUES( ? , ? , ? , ? )"; 

/**
 * Insert a row into cloud sql
 * @param order
 * @param user
 * @return
 */
@ApiMethod(name = "order.add")
public Order addOrder(Order order, User user) throws OAuthRequestException, 
    IOException, ServiceException {

    this.validateUser(user);

    log.info("adding order to cloud sql: " + order);

    try {
         String url = null;
         if (SystemProperty.environment.value() ==
              SystemProperty.Environment.Value.Production) {
            // Load the class that provides the new "jdbc:google:mysql://" prefix.
            Class.forName("com.mysql.jdbc.GoogleDriver");
            url = "jdbc:google:mysql://your-project-id:your-instance-name/guestbook?user=root";
        } else {
            // Local MySQL instance to use during development.
            Class.forName("com.mysql.jdbc.Driver");
            url = "jdbc:mysql://127.0.0.1:3306/guestbook?user=root";

            // Alternatively, connect to a Google Cloud SQL instance using:
            // jdbc:mysql://ip-address-of-google-cloud-sql-instance:3306/guestbook?user=root
        }
        try(Connection conn = DriverManager.getConnection(url)) {

            PreparedStatement stmt = conn.prepareStatement(INSERT_ORDER_SQL);
            stmt.setString(1, order.getAmount());
            stmt.setString(2, order.getUser());
            stmt.setString(3, "Open");
            stmt.setString(4, order.getAddress());

            stmt.executeUpdate();

        }

    } catch(Exception e) {

        log.log(Level.SEVERE, "Failed to create order", e);
        throw new InternalServerErrorException(e);
    }

    return order;
}

/**
 * Validate the current user 
 * @param user
 */
private void validateUser(User user) throws OAuthRequestException, ServiceException {

    // validate the users domain
    if (user == null) {
        throw new OAuthRequestException("Invalid user.");

    } else {
        String email = user.getEmail().toLowerCase();

        // any other validation
    }

}

}

【讨论】:

  • 这很棒。我想知道在哪里可以找到更多样品?
  • 请同时添加一个 SELECT * omerio
猜你喜欢
  • 1970-01-01
  • 2013-12-30
  • 2015-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多