首页 > 解决方案 > 如何从 App 引擎标准环境访问 memorystore?

问题描述

我们将我们的应用部署在 Google 应用引擎标准环境中。我们需要从我们的应用引擎访问 Memorystore(redis)。

按照文档,我们创建无服务器 VPC 访问连接器并配置应用引擎:

<vpc-access-connector>
  <name>projects/PROJECT_ID/locations/REGION/connectors/CONNECTOR_NAME</name>
</vpc-access-connector>

并设置 IAM 权限。但是我们仍然无法使用 jedis 连接到私有 IP(如 10.0.0.4)的 redis 实例:

Jedis jedis = new Jedis("10.0.0.4");

标签: google-app-engineredisgoogle-cloud-platformgoogle-cloud-memorystore

解决方案


如果您使用gcloud beta app deploy target/SNAPSHOT.

我在 Github 中准备并上传了一个示例。

我是如何在一个新项目中做到的:

  1. 启用App Engine,选择区域us-central(对应us-central1)
  2. 在区域 us-central1 中创建 Memorystore 实例
  3. 在区域 us-central1 中创建了VPC 连接器(目前无法选择其他区域,因此 App Engine 和 Memorystore 都必须在 us-central1 中)
  4. 在以下位置添加了 VPC 连接器appengine-web.xml
<vpc-access-connector>
  <name>projects/PROJECT_ID/locations/us-central1/connectors/CONNECTOR_NAME</name>
</vpc-access-connector>
  1. 修改pom.xml,添加如下依赖:
    <dependency>
       <groupId>redis.clients</groupId>
       <artifactId>jedis</artifactId>
       <version>3.1.0</version>
       <type>jar</type>
       <scope>compile</scope>
    </dependency>
  1. 修改servlet.java文件:
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import redis.clients.jedis.Jedis;

@WebServlet(
    name = "Redis",
    description = "Redis: Connect to Redis",
    urlPatterns = "/redis"
)
public class RedisServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String s;
        try{
                Jedis jedis = new Jedis("10.0.0.4");
                jedis.set("myKey", "It's alive");
                s = "Life test: "+ jedis.get("myKey");
        }catch(Exception e){s = "Couldn't connect "; e.printStackTrace();}

       resp.getWriter().write(s);
  }
}
  1. 运行以下打包和部署:

mvn package(这将创建一个“目标”文件夹)

gcloud beta app deploy target/ARTIFACT_ID-1.0-SNAPSHOT

请注意,它仍处于测试阶段,可能无法非常可靠地工作。


推荐阅读