欧阳梓蓓 发表于 2025-6-6 14:03:08

Google Cloud Function函数访问AWS的Redis服务(二)

  上一章介绍了使用VP嗯将Google Cloud和AWS的网络连通,这里介绍如何使用:使用Google Cloud Function 访问AWS的Redis服务。
一:Google Cloud 创建 一个无服务VPC访问通道:VPC网络-》无服务器VPC访问通道-》ip范围自定义(记住这个ip范围)。

二:AWS添加路由,让这个新建的VPC能访问AWS的网络。有两个地方需要修改。
1:VPC面板-》路由表-》编辑路由表-》添加一个规则:目标就是上面记住的IP范围 10.8.0.0/28。第二个目标就是AWS的虚拟私有网关(创建AWS-VPN时创建的)。
2:VPN的静态路由-》添加静态路由(上面记住的IP范围 10.8.0.0/28)。
两个路由设置完成后,google Cloud新建的无服务VPC就能通过VPN访问AWS了。


 
 三:新建Google Cloud Function,访问AWS的Redis。创建云函数时-》出站流量设置-》选择上面创建的 无服务VPC.

 
函数代码:
const functions = require('@google-cloud/functions-framework');
const Redis = require('ioredis');
// 配置 Redis 客户端
const redis = new Redis({
host: 'redisdb.qbkjf-df-rer-dd',//AWS的redis的端点
port: 6379,
connectTimeout: 10000, // 设置连接超时为 10 秒
retryStrategy: () => null // 禁用自动重试
});

redis.on('error', (err) => {
console.error('----Redis 连接错误:', err);
});

functions.http('helloHttp', async (req, res) => {
    await redis.set('test_key', 'Hello from Google Cloud Function!');
    const result = await redis.get('test_key');
    res.send(`Redis result: ${result}`);
}); 
package.json

{
"dependencies": {
    "@google-cloud/functions-framework": "^3.0.0",
    "ioredis": "^5.3.2"
}

创建完成后就可以调用Cloud Function的http链接,发送请求试试看能不能打印log:

 

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Google Cloud Function函数访问AWS的Redis服务(二)