美文网首页
Redis缓存 - h5首页加载

Redis缓存 - h5首页加载

作者: 我叫Aliya但是被占用了 | 来源:发表于2019-05-22 23:58 被阅读0次

懒加载

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

预加载

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

Redis

  • 下载:从github上下载
  • 配置:redis.windows.conf
    服务端口: port
    密码: requirepass
  • 双击启动服务
  • 启动客户端: > redis-cli -p 8888
  • 验证密码: > auth 密码
  • 创建修改数据: > set BBB 222
  • 取:> get BBB
  • 删:> del BBB
  • 哈希值:> hset hash1 myid 1
  • > hget hash1 myid
  • > hdel hash1 myid
  • 取所有键:> keys * (*为通配符)
  • 哈希下的键: > hkeys hash1 *
  • ...

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缓存

相关文章