ioredis โ
ไธไธชๆต่ก็ Redis ๅฎขๆท็ซฏๅบ๏ผ็นๅซ้็จไบ Node.js ็ฏๅข๏ผๆฏๆ Redis ้็พคใๅๅธๅผ Redis ๅไบๅก็ญ็นๆงใ ๅฎๆไพไบไธฐๅฏ็ API ๅ่พ้ซ็ๆง่ฝ๏ผๅฏไปฅๆนไพฟๅฐไธ Redis ๆๅกๅจ่ฟ่กไบคไบใ
https://www.npmjs.com/package/ioredis
install โ
bash
npm install ioredis
usage โ
js
import Redis from "ioredis";
const redis = new Redis({
host: "localhost",
port: 6379,
});
// string
redis.set("name", "123");
redis.get("name").then((res) => {
console.log(res);
});
redis.setex("xxx", 5, "xxx");
// set
redis.sadd("myset", 1, 2, 3, 4, 5);
redis.smembers("myset").then((res) => {
console.log(res);
});
redis.srem("myset", 5);
redis.sismember("myset", 8).then((res) => {
console.log(res);
});
// hash
redis.hset("myhash", "name", "ms");
redis.hset("myhash", "age", 18);
redis.hset("myhash", "sex", 0);
redis.hdel("myhash", "sex");
redis.hgetall("myhash").then((res) => {
console.log(res);
});
// list
redis.lpush("mylist", 1, 2, 3);
redis.rpush("mylist", 8, 9, 0);
redis.llen("mylist").then((res) => {
console.log(res);
});
redis.lrange("mylist", 0, -1).then((res) => {
console.log(res);
});
ๅๅธ่ฎข้ โ
js
import Redis from "ioredis";
const redis = new Redis({
host: "localhost",
port: 6379,
});
const redis2 = new Redis({
host: "localhost",
port: 6379,
});
// ่ฎข้
้ข้
redis.subscribe("news").then((err, count) => {
if (err) {
console.error("Failed to subscribe:", err);
} else {
console.log(`Subscribed to ${count} channel(s).`);
}
});
// ็ๅฌๆถๆฏ
redis.on("message", (channel, message) => {
console.log(channel, message, "--- I am redis");
});
// ๅๅธๆถๆฏ
redis2.publish("news", "I am redis2");
redis2.publish("news", "I am redis2");