安装成功后,进入redis根目录,运行:
redis-server redis.windows.conf
成功显示:
依赖包安装:
npm install koa-generic-session koa-redis
使用演示:
1 const Koa = require(‘koa‘) 2 const redisStore = require(‘koa-redis‘) 3 const session = require(‘koa-generic-session‘) 4 5 const app = new Koa() 6 7 // 数据库对象 8 const store = redisStore().client 9 10 // 用作于session加密处理 11 app.keys = [‘keys‘, ‘keyskeys‘] 12 13 app.use(session({ 14 // options 15 key: "SESSION_ID", 16 prefix: "pref", 17 store: redisStore() 18 })) 19 20 app.use(async ctx => { 21 if (ctx.request.url === ‘/set‘) { 22 // 设置session 23 ctx.session = { 24 user_id: Math.random().toString(16).slice(2).toUpperCase(), 25 count: 0 26 } 27 28 // 直接操作redis 29 await store.hset(‘name‘, ‘test‘, ‘messi‘) 30 31 ctx.body = { 32 code: 0 33 } 34 } 35 36 // 输出信息 37 if (ctx.request.url === ‘/‘) { 38 const name = await store.hget(‘name‘, ‘test‘) 39 40 ctx.session.count++ 41 42 ctx.body = { 43 name, 44 session: ctx.session 45 } 46 } 47 }) 48 49 app.listen(4000, () => { 50 console.log(‘server running at:4000‘) 51 })
52
运行:
node demo.js
效果:
原文:https://www.cnblogs.com/caimuguodexiaohongmao/p/11807195.html