Redis了解一下

最近一直在忙活后台,系统是Koa+MySql+Redis。redis

以前不多接触Redis,如今简单认识和总结一下:数据库

一、什么是Redisnpm

Redis全称为:Remote Dictionary Server(远程数据服务),是一个key-value存储系统。服务器

二、特色:ui

1)读写效率高this

Redis之内存做为数据存储介质,因此读写数据的效率极高,远远超过数据库。以设置和获取一个256字节字符串为例,它的读取速度可高达110000次/s,写速度高达81000次/s。spa

2)存储特性code

储存在Redis中的数据是持久化的,断电或重启后,数据也不会丢失。由于Redis的存储分为内存存储、磁盘存储和log文件三部分,重启后,Redis能够从磁盘从新将数据加载到内存中,这些能够经过配置文件对其进行配置,正由于这样,Redis才能实现持久化。blog

三、用法内存

在Node环境中实现增删查

module.exports = new (function () {
    var self = this;
    var redis = require("redis");
    var client = null;
    this.init = function (host, port) {
        client = redis.createClient(port || 6379, host || '127.0.0.1', {});
    };
    this.getCache = function (key, call) {
        !client && (self.init());
        return new Promise(function (res, rej) {
            call = call || res;
            client.get(key, function (err, v) {
                if (v) {
                    if (v.indexOf('obj-') === 0) {
                        v = v.slice(4);
                        call(JSON.parse(v));
                    } else if (v.indexOf('str-') === 0) {
                        call(v.slice(4));
                    } else {
                        call(v);
                    }
                } else {
                    call();
                }
            });
        });
    };
    this.setCache = function (key, value, expire) {
        !client && (self.init());
        var v = value;
        if (typeof value == 'object') {
            v = JSON.stringify(value);
            v = 'obj-' + v;
        } else {
            v = 'str-' + v;
        }
        client.set(key, v);
        client.expire(key, expire || 72000 * 60 * 1000);
    };
    this.clearCache = function (keys) {
        !client && (self.init());
        for (var i = 0; i < keys.length; i++) {
            client.del(keys[i]);
        }
    };
})();

要先npm一下redis哦

四、场景应用

由于Redis交换数据快,因此在服务器中经常使用来存储一些须要频繁调取的数据,这样能够大大节省系统直接读取磁盘来得到数据的I/O开销,更重要的是能够极大提高速度。

能够实现时间调度,好比在一些订单有明确时效的场景中应用。

相关文章
相关标签/搜索