require ioredis
const Redis = require('ioredis');
const fs = require('fs');
const tlsSettings = {
rejectUnauthorized: false,
key: fs.readFileSync('/opt/Will_Project/formdataAPI/certificate/ys_client.key', 'ascii'),
cert: fs.readFileSync('/opt/Will_Project/formdataAPI/certificate/ys_client.crt', 'ascii'),
ca: [fs.readFileSync('/opt/Will_Project/formdataAPI/certificate/ys_ca.key', 'ascii')]
};
const redis = new Redis({
host: '127.0.0.1',
port: 6379,
tls: tlsSettings,
});
SELECT -- 選擇 DB: 0 ~15
function selectDB(dbNumber){
return new Promise((resolve, reject) => {
redis.select(dbNumber, () => {
console.log(new Date(), 'Redis Client Connect To DB',dbNumber);
resolve()
})
});
}
SET -- 新增、更新資料
function setKey(key, data ){
return new Promise((resolve, reject) => {
redis.set(key, JSON.stringify(data), function(err, result) {
if (err) reject(err)
console.log(new Date(), 'Set Key',key,'Result ->' + result);
resolve(result);
})
})
}
SET KEY EXPIRE -- 設定資料到期時間,單位為秒
ex: setKeyExpire('1770ZZ:inLane', data, 300) //設定此資料expire time - 300秒
function setKeyExpire(key, data, expireTime ){
return new Promise((resolve, reject) => {
redis.set(key, JSON.stringify(data), 'ex', expireTime, function(err, result) {
if (err) reject(err)
console.log(new Date(), 'Set Key',key,'Expire Time Result ->' + result);
resolve(result);
})
})
}
GET -- 取得資料
function getKey(key){
return new Promise((resolve, reject) => {
redis.get(key, function(err, result) {
if (err) reject(err)
console.log(new Date(), 'Get Key',key,'Result ->' + result);
resolve(result);
})
})
}
DEL -- 刪除資料
function delKey(key){
return new Promise((resolve, reject) => {
redis.del(key, function(err, result) {
if (err) reject(err)
console.log(new Date(), 'Del Key',key,'Result' + result);
resolve(result);
})
})
}
LPUSH -- 新增 List 資料
function lpushKey(key, value){
return new Promise((resolve, reject) => {
redis.lpush(key, value, function(err, result) {
if (err) reject(err)
console.log(new Date(), 'LPUSH Key',key,'Result ->' + result);
resolve(result);
})
})
}
LRANGE -- 取得 List 資料
function getListKey(key, startIndex, endIndex){
return new Promise((resolve, reject) => {
redis.lrange(key, startIndex, endIndex, function(err, result) {
if (err) reject(err)
console.log(new Date(), 'LRANGE Key',key,'Result ->' + result);
resolve(result);
})
})
}
SCAN -- 模糊搜尋key
ex: scanKey('3896NN*')
function scanKey(matchKey, dbNumber){
return new Promise((resolve, reject) => {
if (dbNumber !== undefined) redis.select(dbNumber)
const stream = redis.scanStream({
match: matchKey
});
let result_array = []
stream.on("data", (resultKeys) => {
for (let i = 0; i < resultKeys.length; i++) {
result_array.push(resultKeys[i])
//console.log(resultKeys[i]);
}
});
stream.on("end", () => {
console.log(new Date(), "All keys have been visited");
resolve(result_array)
});
})
}
Return to Top