国际惯例,先简单介绍下redis。
redis是什么
REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统。
Redis是一个开源的使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。
它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Hash), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型。
相关git
koakoa-routerkoa-bodynode_redisAnotherRedisDesktopManager
安装redis
安装redis,网上教程很多,这里就不多说,自行搜索一下哈。(本文介绍的是在Windows环境下)
安装完redis后,运行redis-server.exe
,搭配使用redis可视化管理工具 → AnotherRedisDesktopManager
node下安装redis
支持所有redis的命令,redis文档
npm install redis
官方使用示例
var redis = require("redis"), client = redis.createClient(); //如果要切换数据库,可以使用下面命令 // client.select(3, function() { /* ... */ }); client.on("error", function (err) { console.log("Error " + err); }); client.set("string key", "string val", redis.print); client.hset("hash key", "hashtest 1", "some value", redis.print); client.hset(["hash key", "hashtest 2", "some other value"], redis.print); client.hkeys("hash key", function (err, replies) { console.log(replies.length + " replies:"); replies.forEach(function (reply, i) { console.log(" " + i + ": " + reply); }); client.quit(); });
如果node版本是V8或更高的,还可以使用同步
const {promisify} = require('util'); const getAsync = promisify(client.get).bind(client); return getAsync('foo').then(function(res) { console.log(res); // => 'bar' }); //或者使用async await async myFunc() { const res = await getAsync('foo'); console.log(res); }
实际使用
koa + redis 进行增删改查,使用redis中的DB 3
增:添加一个IP ,默认值为0
请求地址 | |
请求方式
|
POST
|
请求参数
|
{
“ip”: “192.168.2.1”
}
|
删:删除IP
请求地址 | http://localhost:3001/gateway?ip=192.168.2.1 |
请求方式
|
DELETE
|
请求参数
|
{
“ip”: “192.168.2.1”
}
|
改:修改IP 的value
请求地址 | http://localhost:3001/gateway |
请求方式
|
PUT |
请求参数
|
{
“ip”: “192.168.2.1”,
“value”:”222″
}
|
查:查询IP的value
请求地址 | http://localhost:3001/gateway?ip=192.168.2.1 |
请求方式
|
GET |
请求参数
|
{
“ip”: “192.168.2.1”
}
|
核心代码
//app.js const Koa = require('koa') const router = require('./routes/index') const app = new Koa() app.use(router.routes()).use(router.allowedMethods()); app.listen(3001) console.log("服务启动成功,端口号:3001 ")
//路由 routes/index.js const Router = require('koa-router'); const koaBody = require('koa-body'); const testController = require('../controllers/test') const router = new Router() //test router.get('/gateway',testController.assignServer)//分配 router.post('/gateway',koaBody(),testController.registerServer)//注册 router.put('/gateway',koaBody(),testController.updateServer)//更新 router.delete('/gateway',testController.deleteServer)//注销 module.exports = router
//封装redis util/redis.js const redis = require("redis"); const { promisify } = require('util'); //Redis 命令参考 http://doc.redisfans.com/index.html /** * * @param {*} db 需要切换的DB,不传则默认DB 0 */ function Client(num){ let db = num || 0 let client = redis.createClient({db}); //需要使用同步函数,按照如下定义即可 this.exists = promisify(client.exists).bind(client); this.keys = promisify(client.keys).bind(client); this.set = promisify(client.set).bind(client); this.get = promisify(client.get).bind(client); this.del = promisify(client.del).bind(client); this.incr = promisify(client.incr).bind(client); this.decr = promisify(client.decr).bind(client); this.lpush = promisify(client.lpush).bind(client); this.hexists = promisify(client.hexists).bind(client); this.hgetall = promisify(client.hgetall).bind(client); this.hset = promisify(client.hset).bind(client); this.hmset = promisify(client.hmset).bind(client); this.hget = promisify(client.hget).bind(client); this.hincrby = promisify(client.hincrby).bind(client); this.hdel = promisify(client.hdel).bind(client); this.hvals = promisify(client.hvals).bind(client); this.hscan = promisify(client.hscan).bind(client); this.sadd = promisify(client.sadd).bind(client); this.smembers = promisify(client.smembers).bind(client); this.scard = promisify(client.scard).bind(client); this.srem = promisify(client.srem).bind(client); return this; } module.exports = Client
业务处理代码
//controllers/test.js const Client = require('../util/redis') class TestController { /* 查询 */ static async get(ctx) { let ip = ctx.request.query.ip; const client = new Client(3); try { let res = await client.get(ip); ctx.body = { data:res } } catch (err) { ctx.body = { message:err } } } /* 增 */ static async add(ctx) { let ip = ctx.request.body.ip; const client = new Client(3); try { let old = await client.exists(ip); if (old) { ctx.error(false, "添加失败, ip已存在") } else { await client.set(ip, 0); ctx.body = { message:"添加成功" } } } catch (err) { ctx.body = { message:err } } } /* 改 */ static async update(ctx) { let ip = ctx.request.body.ip, value = ctx.request.body.value; let isDecr; let client = new Client(3); //gateway在REDIS中的默认DB 为0 try { let old = await client.exists(ip);//先查询 if (old) {//存在 await client.set(ip, value); ctx.body = { message:"修改成功" } } else { ctx.body = { message:"修改失败,IP不存在" } } } catch (err) { ctx.body = { message:err } } } /** * 删 */ static async delete(ctx) { let ip = ctx.request.query.ip; const client = new Client(3); try { let old = await client.exists(ip);//先查询 if (old) {//存在 await client.del(ip); ctx.body = { message:"删除成功" } } else { ctx.body = { message:"删除失败,IP不存在" } } } catch (err) { ctx.body = { message:err } } } } module.exports = TestController
完整代码
完整代码
代码下载到本地后,进入文件夹根目录,输入命令
npm i
安装完node包后再运行
node app.js