笔记:后端 - Redis
生活随笔
收集整理的這篇文章主要介紹了
笔记:后端 - Redis
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Redis學習
最近在向node后臺開發看齊,所以了解了一些關于redis的知識,這里作為筆記
-
安裝redis
使用home-brew
brew install redis
成功的提示信息
To have launchd start redis at login: ln -sfv /usr/local/opt/redis/*.plist ~/Library/LaunchAgents Then to load redis now: launchctl load ~/Library/LaunchAgents/homebrew.mxcl.redis.plist Or, if you don’t want/need launchctl, you can just run: redis-server /usr/local/etc/redis.conf 復制代碼使用cat命令查看配置信息
cat /usr/local/etc/redis.conf
其中指定了端口等信息
bind 127.0.0.1 ::1 bind 127.0.0.1 port 6379 tcp-backlog 511 timeout 0 tcp-keepalive 300 ... 復制代碼- 啟動redis redis-server /usr/local/etc/redis.conf 終端輸出
這里可以看到redis啟動成功,監聽的端口是6379 新開一個tab窗口 輸入redis-cli ping 可以看到控制臺輸出PONG 這就說明redis啟動成功
- 關閉redis
- 在啟動窗口按cmd+c或者直接關掉窗口結束進程
- 執行redis-cli shutdown 輸出redis-cli ping檢驗 控制臺打印Could not connect to Redis at 127.0.0.1:6379: Connection refused 說明關閉成功
node端的簡單使用
-
node安裝redis npm install redis --save
-
啟動redis客戶端
const redis = require('redis'); // 你啟動的redis端口和ip地址+options(可去官網自行查閱資料) const client = redis.createClient(6379, '127.0.0.1', {}); // 監聽錯誤 client.on('error', (err) => {console.log(err); }) // 設置普通的string client.set("string key", "string val", redis.print); // 設置hash值 client.hset("hash key", "hashtest 1", "some value", redis.print); client.hset(["hash key", "hashtest 2", "some other value"], redis.print); // 設置map值 client.mset('key1', 'val1', ... 'keyn', 'valn', '[callback]'); //循環遍歷 client.hkeys("hash key", function (err, replies) {console.log(replies.length + " replies:");replies.forEach(function (reply, i) {console.log(" " + i + ": " + reply);});// 退出client.quit(); }); 復制代碼更多命令使用請參考:?github.com/NodeRedis/n…
-
漂流瓶小功能
-
throw方法
exports.throw = (bottle, callback) => {bottle.time = bottle.time || Date.now();const bottleId = Math.random().toString(16);const type = {male: 0,female: 1};console.log('at redis.js:', bottle);/*client.SELECT選擇數據庫編號*/client.SELECT(type[bottle.type], function (event) {console.log(event);/*client.HMSET 保存哈希鍵值*/client.HMSET(bottleId, bottle, function (err, result) {if (err) {return callback({code: 0,msg: "過會兒再來試試吧!"});}console.log('at redis.js:', result);callback({code: 1,msg: result});/*設置過期時間為1天*/client.EXPIRE(bottleId, 86400);});});} 復制代碼 -
pick方法
exports.pick = function (info, callback) {const type = {all: Math.round(Math.random()),male: 0,female: 1};console.log('info is:', info);info.type = info.type || 'all';client.SELECT(type[info.type], function () {/*隨機返回當前數據庫的一個鍵*/client.RANDOMKEY(function (err, bottleId) {if (!bottleId) {return callback({code: 0,msg: "大海空空如也..."});}/*根據key返回哈希對象*/client.HGETALL(bottleId, function (err, bottle) {if (err) {return callback({code: 0,msg: "漂流瓶破損了..."});}callback({code: 1,msg: bottle});/*根據key刪除鍵值*/client.DEL(bottleId);});});});} 復制代碼- app.js
到這里已經跑通了程序,盡情享受redis吧~
項目地址
-
轉載于:https://juejin.im/post/5b9fb826f265da0aa664b529
總結
以上是生活随笔為你收集整理的笔记:后端 - Redis的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java按比例之原图生成缩略图
- 下一篇: 学习笔记2