1. 启动本机redis:在终端输入
redis-server
默认端口号为:6379
注意:这个终端不要关闭,关闭了之后redis也关了
2. 打开redis客户端测试一下:新开一个终端,输入
redis-cli
127.0.0.1:6379> set name '哈哈'
OK
127.0.0.1:6379> get name
"\xe5\x93\x88\xe5\x93\x88"
127.0.0.1:6379> set site 'www.baidu.com'
OK
127.0.0.1:6379> get site
"www.baidu.com"
127.0.0.1:6379> keys *
1) "name"
2) "site"
127.0.0.1:6379> exit
二. 在Koa中使用redis
npm i redis --save
npm i koa-redis koa-generic-session --save
index.js:
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
const session = require('koa-generic-session')
// 使用redis做内存数据库,访问更快
const redisStore = require('koa-redis')
const koaStatic = require('koa-static')
// 配置session中间件
app.keys = ['IOdhakw23792#'] // session 密钥
app.use(session({
key: 'projname.sid', // cookie name 默认是 `koa.sid`
prefix: 'projname:sess:', // redis key 的前缀,默认是 `koa:sess:`
cookie: {
path: '/',
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000 // 单位 ms
},
store: redisStore({
all: '127.0.0.1:6379'
})
}))
router.get('/login',async(ctx)=>{
// 设置session
ctx.session.userinfo='张三'
ctx.body='登录成功'
})
router.get('/json', async (ctx, next) => {
const session = ctx.session
if (session.viewNum == null) {
session.viewNum = 0
}
session.viewNum++
ctx.body = {
title: 'koa2 json',
viewNum: session.viewNum
}
})
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000, () => {
console.log('starting at port 3000');
});
在/conf/db.js中编写redis的地址和端口:
/**
* @description redis存储配置
*/
let REDIS_CONF = {
port: 6379,
host: '127.0.0.1'
}
module.exports = {
REDIS_CONF
}
在/cache/_redis.js中编写redis的连接方法get和set:
/**
* /cache/_redis.js
* redis的方法get和set
*/
const redis = require('redis')
const { REDIS_CONF } = require('../conf/db')
// 创建客户端
const redisClient = redis.createClient(REDIS_CONF.port, REDIS_CONF.host)
redisClient.on('error', err => {
console.error('redis error', err)
})
/**
* redis set
* @param {string} key 键
* @param {string} val 值
* @param {number} timeout 过期时间,单位 s
*/
function set(key, val, timeout = 60 * 60) {
if (typeof val === 'object') {
val = JSON.stringify(val)
}
redisClient.set(key, val)
redisClient.expire(key, timeout)
}
/**
* redis get
* @param {string} key 键
*/
function get(key) {
const promise = new Promise((resolve, reject) => {
redisClient.get(key, (err, val) => {
if (err) {
reject(err)
return
}
if (val == null) {
resolve(null)
return
}
try {
resolve(
JSON.parse(val)
)
} catch (ex) {
resolve(val)
}
})
})
return promise
}
module.exports = {
set,
get
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)