还有一种操作,用云引擎转发,我们内部文档里有个 demo,供参考:
在示例项目上修改 app.js:
var expressWs = require('express-ws')
expressWs(app)
app.ws('/cache-proxy', (ws, req) => {
const net = require('net')
const websocketStream = require('websocket-stream/stream')
const pipe = require('pump')
const {URL} = require('url')
if (req.headers['authorization'] !== 'password') {
ws.send('unauthorized')
return ws.close()
}
const redisUrl = new URL(process.env['REDIS_URL_BfmxnBi0KO'])
console.log('cache-proxy connected from', req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress)
const wsStream = websocketStream(ws, {
binary: true,
});
const redisConnection = net.createConnection(redisUrl.port, redisUrl.hostname)
redisConnection.on('error', (err) => {
console.log('redisConnection', err)
})
const onError = (err) => {
console.log('onError', err)
}
redisConnection.on('connect', () => {
pipe(wsStream, redisConnection, onError)
pipe(redisConnection, wsStream, onError)
})
})
注意修改其中的密码和 LeanCache 实例名,然后安装以下依赖:
npm install express-ws websocket-stream pump
然后部署到线上的云引擎。
本地安装 websocat:
// 假设用的是 mac 系统,其他系统可以用别的方法安装
brew install websocat
将线上的 LeanCache 转发到本地(注意替换密码和云引擎域名):
websocat -E -H 'Authorization: password' --binary tcp-listen:127.0.0.1:5678 wss://new2.cn-e1.leanapp.cn/cache-proxy
然后本地的程序就可以在 127.0.0.1:5678
使用 Redis 协议去连接 LeanCache 了。不过因为云引擎的负载均衡会关闭 60 秒无数据写入的连接,所以客户端可能会比较频繁地重连。