App Engine标准环境如何访问memorystore?

How to access memorystore from App engine standard environment?

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

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

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

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

Jedis jedis = new Jedis("10.0.0.4");

如果您使用 gcloud beta app deploy target/SNAPSHOT 部署它应该可以工作。

我准备并上传了 sample in Github

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

  1. 已启用 App Engine,选择区域 us-central(对应于 us-central1)
  2. 在区域 us-central1 中创建了 Memorystore 实例
  3. 已在区域 us-central1 中创建 VPC Connector(目前无法选择其他区域,因此 App Engine 和 Memorystore 都必须在 us-central1 中)
  4. appengine-web.xml 中添加了 VPC 连接器:
<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(这将创建一个 "target" 文件夹)

gcloud beta app deploy target/ARTIFACT_ID-1.0-SNAPSHOT

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