Redis缓存 - h5首页加载

2019-05-22  本文已影响0人  我叫Aliya但是被占用了

懒加载

使用到某模块,浏览器才去加载其代码

预加载

将未来可能会用到的资源提前请求加载到本地,这样后面在需要用到时就直接从缓存取资源

Redis

node中的redis

npm标准包redis

npm install redis
// redis_helper.js
const redis = require("redis");
const client = redis.createClient(6379, '127.0.0.1');

client.auth('123456')

client.on("error", function (err) {
  console.error("redis error: " + err);
});
client.on("ready", function () {
  console.log("redis is ready ");
});

// if you'd like to select database 3, instead of 0 (default), call
// client.select(3, function() { /* ... */ });

class redis_helper {

  get (key) {
    return Promise ((res, rej) => {
      let keys = key.split('.')
      if (keys.length == 1) {
        client.get(key, function (err, reply) {
          console.log(reply.toString()); // Will print `OK`
          res(reply)
        });
      } else {
        client.hget(keys[0], keys[1], function (err, reply) {
          console.log(reply.toString());
          res(reply)
        });
      }
    })
  }

  set (key, value) {
    let keys = key.split('.')
    if (keys.length == 1) {
      client.set(key, value, redis.print);
    } else {
      client.hset(keys[0], keys[1], value, redis.print);
    }
  }

}

// client.quit(); 关闭连接
module.exports = redis_helper
  1. 前端直接访问redis,redis没有值访问接口下拉缓存再返回。值变化由后端触发更新redis缓存
  2. 前端直接访问后端接口,后端先取redis,没有值从db中取缓存再返回。值变化的同时更新redis缓存
上一篇下一篇

猜你喜欢

热点阅读