一、Redis 簡介
無論是什么類型的應用,都少不了和數據打交道。尤其是一些復雜的應用場景,都少不了一個高效可靠的數據庫。例如日常開發中最常見的 MySQL 等關系型數據庫,讓數據的存儲、檢索輕松簡單起來,甚至可以輕松地處理百萬量級的數據。 而從廣義上講,數據庫可以分為二大類,分別是關系型數據庫與非關系型數據庫,上一期我們講過的 SQLite 即為關系型數據庫,而本文的 Redis 則是非關系型數據庫,是一個以 BSD 協議發行的、開源免費的,并具備極高性能的鍵值數據庫。同時 Redis 也是業務應用中最為常見的“緩存”數據庫。 為了方便應用開發, EdgerOS 同樣引入了 Redis 的客戶端模塊,滿足不同業務場景下對數據處理的需求,開發者可以使用改客戶端方便地連接并使用 Redis 服務器。
二、引入模塊
EdgerOS 將 Redis 的客戶端封裝在了 redis 模塊中,在開發中要使用時需要先引入該模塊:
const redis = require ( 'redis ') ;
三、創建客戶端
使用 createClient 方法來創建 Redis 客戶端,調用此方法會返回一個 RedisClient 的對象; redis.createClient([options]) returns: {Redis} 返回一個 RedisClient 的對象 示例如下:
const redis = require ( 'redis ') ;
const client = redis. createClient ( { host: '10 . 4.0 . 180 ', port: 6379 , detect_buffers: true
} ) ;
const client = redis. createClient ( { host: '10 . 4.0 . 180 ', port: 6379 , retry_strategy: function ( options) { if ( options. error && options. error. code == = 'ECONNREFUSED ') { return new Error ( 'The server refused the connection') ; } if ( options. total_retry_time > 1000 * 60 * 60 ) { return new Error ( 'Retry time exhausted') ; } if ( options. attempt > 10 ) { return undefined; } return Math . min ( options. attempt * 100 , 3000 ) ; } , } ) ;
相關選項說明: detect_buffers:回復是否使用 Buffer 選項 retry_strategy:將選項對象作為參數的一種函數
四、保存與讀取數據
使用 hmset 方法來保存數據, 允許存儲多組數據: client.hmset(hash, key1, val1, …keyN, valN[, callback]) val {String | Buffer | Number | Date} 字段的值 使用 hgetall 方法來讀取數據: client.hgetall(hash[, callback]) 示例如下:
const redis = require ( 'redis ') ;
const client = redis. createClient ( { host: '10 . 4.0 . 180 ', port: 6379 } ) ; client. hmset ( 'key ', 'foo ', 'bar ', 'hello ', 'world ') ; client. hgetall ( 'key ', function ( err, value) { console. log ( value. foo) ; console. log ( value. hello) ;
} ) ;
五、訂閱與發布
使用 publish 方法進行客戶端消息發布: client.publish(channel, message) message {String | Number | Buffer | Date} 發布的消息 使用 subscribe 方法對服務端的消息進行訂閱: client.subscribe(channel) 示例如下:
const redis = require ( 'redis ') ; const subscriber = redis. createClient ( { host: '10 . 4.0 . 180 ', port: 6379 } ) ;
const publisher = redis. createClient ( { host: '10 . 4.0 . 180 ', port: 6379 } ) ; let messageCount = 0 ; subscriber. on ( 'subscribe ', function ( channel, count) { publisher. publish ( 'a channel', 'a message') ; publisher. publish ( 'a channel', 'another message') ;
} ) ; subscriber. on ( 'message ', function ( channel, message) { messageCount += 1 ; console. log ( "Subscriber received message in channel '" + channel + "': " + message) ; if ( messageCount == = 2 ) { subscriber. unsubscribe ( ) ; subscriber. quit ( ) ; publisher. quit ( ) ; }
} ) ; subscriber. subscribe ( 'a channel') ;
至此,Redis 客戶端的主要功能與實現相信大家都有一個初步的認識,由于篇幅所限,不能完整詳細的闡述 Redis Client 模塊的所有功能,有興趣的同學可以從我們 EdgerOS 官網獲取完整信息。而我們EdgerOS 除了提供 Redis 客戶端以外, 還有像非關系型數據庫中的 Mysql 客戶端等, 都可在官網中獲取相關信息,希望本文可以對您的應用開發有所裨益。