如何连接到 Google Cloud SQL PostgresQL

Posted

技术标签:

【中文标题】如何连接到 Google Cloud SQL PostgresQL【英文标题】:How to connect to Google CloudSQL PostgresSQL 【发布时间】:2019-08-05 16:02:38 【问题描述】:

我尝试使用 Gorm golang 连接到 Google CloudSQL PostgresSQL,但似乎无法正常工作。

这是代码

func InitDB() *gorm.DB 

    psqlInfo := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", os.Getenv("DB_HOST"), os.Getenv("DB_PORT"), os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_NAME"))
    db, err := gorm.Open("postgres", psqlInfo)
    if err != nil 
        fmt.Println("Failed to connect to the Database")
    
    fmt.Println("Connected to the Database")
    DB = db
    return DB

如果我使用本地主机配置一切正常。有关 cloudSQL 配置,请参阅我的 .env 文件

DB_HOST=trader-234509:us-central1:testv1
DB_PORT=5432
DB_USER=username
DB_NAME=testv1
DB_PASSWORD=

错误是说

dial tcp:lookup trader-234509:us-central1:testv1: no such host 恐慌:运行时错误:无效的内存地址或零指针取消引用 [信号SIGSEGV:分段违规代码=0x1 addr=0x40 pc=0x164681d]

我的本​​地配置(这个工作正常)

DB_HOST=localhost
DB_PORT=5432
DB_USER=username
DB_NAME=test
DB_PASSWORD=

我是不是做错了什么?

【问题讨论】:

您是否尝试过使用 cloudsql 实例的 IP 地址作为 hostaddr 而不是 host?如此处所示:cloud.google.com/sql/docs/postgres/connect-admin-ip#connect 我使用 gorm doc.gorm.io/database.html#connecting-to-a-database hostaddr 不是库规则的一部分 在这种情况下,您是否尝试过使用实例 IP 作为host 如果您在谈论公共 ip。是的,我试过了,还是报错 感谢您的帮助和时间来帮助我! 【参考方案1】:

以下是我从 AppEngine 连接的大致方式:

import (
  _ "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/postgres"
  "fmt"
  "gorm.io/driver/postgres"
  "gorm.io/gorm"
)

func New() (*gorm.DB, error) 
  user := "theuser"
  password := "apassword"
  dbHost := "my-project:the-region:my-db-instance-name"
  databaseName := "mydbname"

  connString := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s", dbHost, user, databaseName, password)
  
  return gorm.Open(postgres.New(postgres.Config
    DriverName: "cloudsqlpostgres",
    DSN: connString,
  ))

【讨论】:

【参考方案2】:

Cloud SQL 暂不支持直接连接第三方应用的实例名称,详情:https://cloud.google.com/sql/docs/mysql/connect-external-app

根据我的经验,有两种解决方案:

    按照上述说明,您可以按照以下步骤设置云代理,连接流程为:Golang 应用程序 -> 云代理 -> 云 SQL 这种方法很灵活,您可以使用防火墙控制连接。 但是您必须花费额外的$$来维护服务器和这个云代理实例,我也听说云代理可能存在一些性能问题但我目前没有确切的证据

    为 Cloud SQL 实例分配私有 IP,请参考https://cloud.google.com/sql/docs/mysql/private-ip,以便您的应用程序可以使用此 IP 直接访问数据库。 权衡很明显,应用程序必须在项目的同一网络中,但这是一种更方便的方法,尤其是。您的所有应用程序都托管在同一个网络中

我没有尝试公共 IP 访问方法,因为如果需要远程网络连接,云代理正是我所需要的

简而言之,您需要使用选项 2 在 VM 或其他 Google 托管服务中部署代码,或者设置云代理以支持选项 1 的本地调试 希望对你有帮助

【讨论】:

以上是关于如何连接到 Google Cloud SQL PostgresQL的主要内容,如果未能解决你的问题,请参考以下文章

将Sequelize连接到Google Cloud SQL

使用 .Net Framework 连接到 Google Cloud SQL

将 Django 连接到 Google Cloud SQL

pgadmin4 连接到 Google Cloud SQL 中的 postgres

在 GKE 中,typeorm 无法连接到 Google Cloud SQL 代理

在 perl 中从 GCE 远程连接到 Google Cloud SQL 时出错