google-app-engine - 如何从 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");
解决方案
如果您使用gcloud beta app deploy target/SNAPSHOT
.
我在 Github 中准备并上传了一个示例。
我是如何在一个新项目中做到的:
- 启用App Engine,选择区域us-central(对应us-central1)
- 在区域 us-central1 中创建 Memorystore 实例
- 在区域 us-central1 中创建了VPC 连接器(目前无法选择其他区域,因此 App Engine 和 Memorystore 都必须在 us-central1 中)
- 在以下位置添加了 VPC 连接器
appengine-web.xml
:
<vpc-access-connector>
<name>projects/PROJECT_ID/locations/us-central1/connectors/CONNECTOR_NAME</name>
</vpc-access-connector>
- 修改
pom.xml
,添加如下依赖:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.1.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
- 修改
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);
}
}
- 运行以下打包和部署:
mvn package
(这将创建一个“目标”文件夹)
gcloud beta app deploy target/ARTIFACT_ID-1.0-SNAPSHOT
请注意,它仍处于测试阶段,可能无法非常可靠地工作。
推荐阅读
- javascript - 在 HTML 源代码中查找所有空链接(包含 href="x" 的空标签)的最常用方法是什么?
- c++ - C++ #include 和 operator<< 重载错误
- javascript - 使用phantomjs的实时网页截图
- c - 读取当前目录,根据文件属性打印结果
- gosu - Gosu类vs增强
- java - 为什么我的 ScheduledExecutorService 会这样工作?
- eclipse - 在 Mac 中从 Eclipse 设置 tomcat
- php - 在PHP中创建一个依赖于事务表的html表
- javascript - 如何从 JavaScript 列表中删除新项目?
- angular - 如何在Angular 6中的文件夹内创建组件