nodejs + Koa2 之Redis安装使用
本机Redis的安装
【mac系统为栗子】
下载
打开官网:https://redis.io/ Download—Stable—Download6.0.4,下载最新稳定版,这里是6.0.4
安装
1.下载完成后,打开命令行工具,执行解压命令(如可以双击解压就更好)
tar zxvf redis-6.0.4.tar.gz
2.将解压后文件夹放到/usr/local
mv redis-6.0.4 /usr/local
3.切换到相应目录
cd /usr/local/redis-6.0.4
4.编译测试
sudo make test
执行后成功如图所示 5.编译安装
sudo make install
6.启动Redis
redis-server
在项目中使用Redis
安装依赖
npm install redis --save
安装oredis包
npm install ioredis --save
创建Redis.js
首先,新建配置文件 Redis.js (文件名可变,根据你项目的需求),目录如下 文件代码
const redisStore = require(koa-redis) const Redisdb = require(ioredis) module.exports = class Redis { constructor () { this.config = { port: 6379, host: 127.0.0.1, db: 0 } this.client = new Redisdb(this.config) this.options = { client: this.client, db: 0 } this.store = redisStore(this.options) } async storeClient () { return this.store.client } async set (key, value, expiryMode, time) { return this.client.set(key, value, expiryMode, time) } async get (key) { return this.client.get(key) } async hmset (key, data) { return this.client.hmset(key, data) } async expire (key, time) { return this.client.expire(key, time) } async hmget (key) { return this.client.hgetall(key) } async getAllKey () { return this.client.keys(*) } }
创建user用户存储到redis,并在缓存获取数据
1.准备工作,这里用到了依赖注入,inversify,将Redis注入到使用缓存的文件里,如下代码所示 UserService.js
将Redis注入进来,方便使用其方法
module.exports = class UserService { constructor (User, Describe, Redis) { this._User = User this._Describe = Describe this._Redis = Redis// redis注入UserService中 }
创建用户,存入缓存中,调用Redis.js中hmset(key,data)方法
async createUser (user) { const key = `${ user.userName}_user` //设置key,因为会有多个用户创建 const a = await this._Redis.hmset(key, user) return user }
获取用户信息,直接从缓存中获取,调用Redis.js中hmget(key)方法
async getUsers () { const keys = await this._Redis.getAllKey()//拿取内存中所有key const data = keys.filter(data => data.endsWith(_user))//筛选出以_user结尾的文件 let users = []//定义数组 for (let usr of data) { const res = await this._Redis.hmget(usr) users.push(res)//遍历并return } return users }
依赖注入文件,增加Redis buildInversifyContainer.js 注入
inversify.decorate(inversify.inject(types.Redis), context.UserService, 2)
context.js
function redisControllers () { const dirPath = path.join(__filename, ../../config/redis/models) const data = fs.readdirSync(dirPath) .map(file => require(path.join(dirPath, file))) .reduce((object, currentValue) => { object[currentValue.name] = currentValue return object }, { }) return data }
function buildContext () { const services = loadServices() const controllers = loadControllers() const redis = redisControllers() const context = { ...models, ...services, ...controllers, ...redis } delete context.Sequelize return context }
调用创建的接口 ,成功后调用获取接口,拿到了证明成功了
验证存储是否成功
redis-cli -h 127.0.0.1 -p 6379
hmget xwr2r_user email//hmget key file
上一篇:
IDEA上Java项目控制台中文乱码