如何在 Google Cloud App Engine 中为 Node.js 使用 Memcache

How to use Memcache in Google Cloud App Engine for Node.js

我正在尝试在 gcloud 标准应用引擎上设置快速服务。 我想使用 memcache 进行会话缓存。

有人能帮我吗,我如何将服务连接到内存缓存?

我的密码是:

var session = require('express-session')
var MemcachedStore = require('connect-memcached')(session);
app.use(session({
  secret: 'appengineFTW',
  key: 'a_key',
  resave: true,
  store: new MemcachedStore({
      hosts: [process.env.MEMCACHE_URL || '127.0.0.1:11211']
  }),
  saveUninitialized: false
}));

prod中的MEMCACHE_URL设置为memcache:11211

错误:连接 ECONNREFUSED 127.0.0.1:11211

1.Create 服务器文件夹。

mkdir server
cd server

2.Copy将server.js文件放入文件夹

const express = require('express');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const MemcachedStore = require('connect-memjs')(session);
const publicIp = require('public-ip');
const crypto = require('crypto');

// Environment variables are defined in app.yaml.
let MEMCACHE_URL = process.env.MEMCACHE_URL || '127.0.0.1:11211';

if (process.env.USE_GAE_MEMCACHE) {
  MEMCACHE_URL = `${process.env.GAE_MEMCACHE_HOST}:${process.env.GAE_MEMCACHE_PORT}`;
}

const app = express();
app.enable('trust proxy');

app.use(cookieParser());
app.use(session({
  secret: 'your-secret-here',
  key: 'view:count',
  proxy: 'true',
  store: new MemcachedStore({
    servers: [MEMCACHE_URL]
  })
}));

app.get('/', (req, res, next) => {
  // Discover requester's public IP address
  publicIp.v4().then((ip) => {
    const userIp = crypto.createHash('sha256').update(ip).digest('hex').substr(0, 7);

    // This shows the hashed IP for each
    res.write(`<div>${userIp}</div>`);

    if (req.session.views) {
      req.session.views += 1;
    } else {
      req.session.views = 1;
    }
    res.end(`Viewed <strong>${req.session.views}</strong> times.`);
  }).catch(next);
});

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log('App listening on port %s', PORT);
  console.log('Press Ctrl+C to quit.');
});

module.exports = app;

3.Create 带有 NPM 或 Yarn 的 package.json 文件:

npm init

4.Install 与 NPM 或 Yarn 的依赖关系:

npm install --save connect-memjs cookie-parser express express-session public-ip

5.Create a memcached instance 与您的 App Engine 应用程序位于同一区域(gcloud app describe 以查找该区域)。记下您的其中一个节点的 IP 地址。

6.Create一个app.yaml文件

runtime: nodejs
env: flex

env_variables:

  MEMCACHE_URL: 10.10.10.10:11211 #your memcached instance ip

7.Deploy App Engine Flex 应用程序

gcloud 应用部署 gcloud 应用程序浏览

  1. 访问 http://YOUR_PROJECT_ID.appspot.com 查看已部署的应用程序。