安装 Redis 和 Node.js
首先确保你的系统上已经安装了 Redis 和 Node.js。对于大多数 Linux 发行版,你可以使用包管理器来安装它们。
在 Ubuntu 上安装 Redis 和 Node.js
sudo apt-get update sudo apt-get install redis-server
对于 Node.js,你可以通过以下命令安装:
curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - sudo apt-get install -y nodejs
在 macOS 上安装 Redis 和 Node.js
你可以使用 Homebrew 来安装 Redis 和 Node.js。
brew install redis brew install node
启动 Redis 服务:
redis-server
使用 Node.js 连接 Redis
为了在 Node.js 中连接 Redis,你需要安装 ioredis 或者 redis 库。这里我们使用 ioredis,因为它提供了更好的性能和更多的功能。
安装 ioredis:
npm install ioredis
然后在你的 Node.js 文件中,你可以这样连接到 Redis:
// www.javascriptcn.com code example
const Redis = require('ioredis');
const redis = new Redis();
redis.set('foo', 'bar')
.then(() => {
console.log('Set foo to bar');
})
.catch(err => {
console.error(err);
});
redis.get('foo')
.then(result => {
console.log(`foo: ${result}`);
})
.catch(err => {
console.error(err);
});Redis 的基本操作
设置键值对
设置键值对是 Redis 最基本的操作之一。你可以使用 set 命令来完成这个操作。
redis.set('username', 'Alice')
.then(() => {
console.log('Set username to Alice');
})
.catch(err => {
console.error(err);
});获取键值
获取键值可以通过 get 命令来实现。
redis.get('username')
.then(result => {
console.log(`Username is ${result}`);
})
.catch(err => {
console.error(err);
});删除键
删除键可以使用 del 命令。
redis.del('username')
.then(() => {
console.log('Deleted username');
})
.catch(err => {
console.error(err);
});检查键是否存在
你可以使用 exists 命令来检查一个键是否存在。
// www.javascriptcn.com code example
redis.exists('username')
.then(result => {
if (result) {
console.log('Username exists');
} else {
console.log('Username does not exist');
}
})
.catch(err => {
console.error(err);
});过期键
你可以使用 expire 命令来设置一个键的过期时间。
// www.javascriptcn.com code example
redis.set('token', 'abc123')
.then(() => {
console.log('Set token to abc123');
})
.catch(err => {
console.error(err);
});
redis.expire('token', 60)
.then(() => {
console.log('Token will expire in 60 seconds');
})
.catch(err => {
console.error(err);
});Redis 数据类型
Redis 支持多种数据类型,包括字符串、列表、集合、有序集合和哈希表。这些数据类型提供了不同的功能,适用于不同的场景。
字符串
字符串是最基本的数据类型,可以用来存储简单的键值对。
// www.javascriptcn.com code example
redis.set('count', 42)
.then(() => {
console.log('Set count to 42');
})
.catch(err => {
console.error(err);
});
redis.get('count')
.then(result => {
console.log(`Count is ${result}`);
})
.catch(err => {
console.error(err);
});列表
列表允许你存储一个有序的字符串列表,支持从列表的两端插入和移除元素。
// www.javascriptcn.com code example
redis.rpush('tasks', 'task1')
.then(() => {
return redis.rpush('tasks', 'task2');
})
.then(() => {
return redis.lrange('tasks', 0, -1);
})
.then(tasks => {
console.log(`Tasks are: ${tasks.join(', ')}`);
})
.catch(err => {
console.error(err);
});集合
集合是一个无序且不重复的字符串列表。它支持添加、删除和检查成员。
// www.javascriptcn.com code example
redis.sadd('members', 'Alice')
.then(() => {
return redis.sadd('members', 'Bob');
})
.then(() => {
return redis.smembers('members');
})
.then(members => {
console.log(`Members are: ${members.join(', ')}`);
})
.catch(err => {
console.error(err);
});有序集合
有序集合类似于集合,但是每个成员都关联一个分数,用于排序。
// www.javascriptcn.com code example
redis.zadd('scores', 100, 'Alice')
.then(() => {
return redis.zadd('scores', 95, 'Bob');
})
.then(() => {
return redis.zrange('scores', 0, -1, 'WITHSCORES');
})
.then(scores => {
console.log(`Scores are: ${scores.join(', ')}`);
})
.catch(err => {
console.error(err);
});哈希表
哈希表是一个字段和值的映射表。
// www.javascriptcn.com code example
redis.hset('profile', 'name', 'Alice')
.then(() => {
return redis.hset('profile', 'age', 30);
})
.then(() => {
return redis.hgetall('profile');
})
.then(profile => {
console.log(`Profile: ${JSON.stringify(profile)}`);
})
.catch(err => {
console.error(err);
});使用 Redis 实现缓存
缓存是一种常见的使用 Redis 的场景。它可以显著提高应用程序的响应速度和减轻数据库的压力。
设置缓存
你可以将经常访问的数据存储在 Redis 中作为缓存。
// www.javascriptcn.com code example
function getFromCache(key) {
return redis.get(key)
.then(result => {
if (result) {
return result;
} else {
// 如果缓存中没有数据,从数据库或其他来源获取数据
return fetchFromDatabase(key)
.then(data => {
redis.set(key, data, 'EX', 3600); // 缓存一小时
return data;
});
}
});
}
function fetchFromDatabase(key) {
// 模拟从数据库获取数据
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Data for ${key}`);
}, 2000);
});
}
// 使用缓存
getFromCache('user1')
.then(data => {
console.log(`Cached data: ${data}`);
})
.catch(err => {
console.error(err);
});清理缓存
有时需要手动清理缓存。例如,当数据发生变化时,可以清除相关的缓存条目。
// www.javascriptcn.com code example
function updateData(key, newData) {
return redis.set(key, newData, 'EX', 3600)
.then(() => {
console.log(`Updated data for ${key}`);
});
}
function invalidateCache(key) {
return redis.del(key)
.then(() => {
console.log(`Invalidated cache for ${key}`);
});
}
updateData('user1', 'New data')
.then(() => {
return invalidateCache('user1');
})
.catch(err => {
console.error(err);
});以上就是 Node.js 中使用 Redis 的基本介绍。通过这些示例,你应该能够开始在你的项目中集成 Redis,并利用其强大的功能。