Redis is a popular NoSQL database, generally used instead of memcached for caching services, and it also supports the persistence of data, with a wide range of application scenarios. We are already familiar with using Redis in Java, so what is the correct posture for using Redis in the node. js and koa.js frameworks?
Redis is fully open source free, adheres to the BSD protocol and is a high-performance Key-value database.
Redis and other Key-value cache products have the following three features:
* Redis support data persistence, can keep the in-memory data on the disk, restart can be loaded again for use.
* Redis not only supports simple key-value types of data, but also provides storage of data structures such as List,set,zset,hash.
* Redis Support data backup, that is, Master-slave mode of data backup.
Redis Common commands can refer to http://www.runoob.com/redis/redis-keys.html
node. JS already has a lot of redis-related libraries, and I've searched the npm.org for about more than 10 of them, often using Redis,co-redis. Because I used KOA as a web framework, I used Koa-redis directly. This article deals with the knowledge of Koa.js,yield generators and promise, which requires some understanding of these concepts first.
Below is the introduction of Redis and koa.js related operations, I am operating under the Mac.
1. Install Redis and start the client and server side
brew install redis
Start the server side redis-server
29322: C .Sep -: the:25.109 # warning:no config file specified, using the default Config. In order to specify a config file use redis-server/path/to/redis.conf29322: M .Sep -: the:25.111* Increased maximum number ofOpen files to10032(It is originally set to1024x768). _._ _.-``__"'-._ _.-`` `. `_."'-._ Redis3.0. 6(00000000/0) -bit.-'` .-```. ```\/ _.,_"'-._ (',.-' | ', ') Running in standalone mode | '-._ '-...-' __...-. '-._| '`_.-' | port:6379 | `-._ `. _/_.-' | pid:29322 `-._ `-._ `-./ _.-' _.-'|`-._`-._ `-.__.-'_.-' _.-' | | `-._`-._ _.-' _.-' | http://redis.io `-._ `-._`-.__.-' _.-'_.-' | '-._ '-._ '-.__.-'_.-' _.-'| | `-._`-._ _.-' _.-'| `-._ `-._`-.__.-'_.- ' _.-' `-._ `-.__.-' _.-' `-._ _.-"' -.__.-'29322: M .Sep -: the:25.116 # Server started, Redis version 3.0.629322: M .Sep -: the:25.116* The server isNow ready to accept connections onPort6379
- Start the client
redis-cli
127.0.0.1:6379[1]> select 0
OK
127.0.0.1:6379> keys *
(empty list or set)
127.0.0.1:6379>
2. Install the node. js and Koa.js,node installation Here is not the case, through the brew install can be.
npm install koa redis koa-redis
You can see that Koa-redis has relied on Co-redis, es6-promisify and other libraries
`-- [email protected]
+-- [email protected]
| `-- [email protected]
| `-- [email protected]
`-- [email protected]
+-- [email protected]
`-- [email protected]
3. Koa.js operation of Redis data
This piece is the focus of this article, because the official documents and examples are not too detailed, not familiar with node's classmates toss up will be more tired, so this article provides a more complete example. The specific code inside the note has been written more clearly.
varSession =require(' Koa-generic-session ');varRedisstore =require(' Koa-redis ');varKOA =require(' KOA ');varRedis =require(' Redis ');//NOTE: Client default is asynchronous callback mode call;//Store.client is Co-redis packaging, return promise, in KOA with yield asynchronous programming is more convenientvarClient = Redis.createclient (6379,"172.19.65.240");varApp = Koa (); app.keys = [' Keys ',' Keykeys '];//var option={host: "172.19.65.240", db:1};varOptions = {client:client, db:1};varstore = Redisstore (options), App.use (session ({Store:store})); App.use ( Function *() { Switch( This. Path) { Case '/get ': Get.call ( This); Break; Case '/testkv '://Save key value if( This. Query.adminid) {yieldStore.client.set ("Test1", This. Query.adminid); }//Read key value synchronously This. BODY =yieldStore.client.get ("Test1"); Break; Case '/testhm '://Operation HashMap varresult =yieldStore.client.hmset ("Hosts","MJR","123","another","All","Home","1234"); Console.log (result);varobj =yieldStore.client.hgetall ("Hosts") Console.dir (obj);//Get the value of HashMap key This. BODY =yieldStore.client.hget ("Hosts","Home");//Save HashMap, use the default callback mode //Client.hset ("Hash Key", "Hashtest 1", "some value", redis.print); //Client.hset (["Hash Key", "Hashtest 2", "Some other value"], redis.print); //Client.hmset ("Hosts", "MJR", "1", "another", "All", "home", "1234"); //Client.hmset (["Key", "Test keys 1", "Test val 1", "Test Keys 2", "Test Val 2"], function (err, res) { //Console.log (res); // }); Break; Case '/testset '://Save set varKey ="Key1"; Store.client.sadd ("Key1","V1"); Store.client.sadd ("Key1","V2"); Store.client.sadd ("Key1","V3");//Read setStore.client.multi (). Sismember (Key,' v1 '). Smembers (key). EXEC ( function (err, replies) {Console.log ("MULTI got"+ Replies.length +"replies"); Replies.foreach ( function (reply, index) {Console.log ("Reply"+ Index +": "+ reply.tostring ()); }); });//Read set This. BODY =yieldStore.client.smembers ("Key1"); Break; Case '/testlist '://Save listStore.client.rpush ("MyList","BBB") Store.client.rpush ("MyList","CCC") Store.client.lpush ("MyList","AAA") This. BODY =yieldStore.client.rpop ("MyList"); Break; Case '/remove ': Remove.call ( This); Break; Case '/regenerate ':yieldRegenerate.call ( This); Break; }}); function get() { varSession = This. session; Session.count = Session.count | |0; session.count++;varTest = Store.client.get ("Test"); Console.log (test); This. BODY = Session.count;} function remove() { This. session =NULL; This. BODY =0;} function *regenerate() {Get.call ( This);yield This. Regeneratesession (); Get.call ( This);} App.listen (8080);
There's a lot of writing about using Redis in the KOA framework, but there's also the use of publish-subscribe, and that's not the point.
Correct posture for using Redis Database in node. js