github分享:入口
个人网盘分享(推荐)
链接:https://pan.baidu.com/s/1c4mBdwhxJshvC3i_fI2_gg
提取码:
5ntg
- 查看系统是否安装redis
- yum info redis
-
- 如果没有安装,执行以下步骤
- 安装epel库
- yum install epel-release -y
- 安装redis
- yum install redis -y
-
- 操作
- 启动:systemctl start redis
- 重启:systemctl restart redis
- 关闭:systemctl stop redis
-
- 设置开机启动
- systemctl enable redis
- brew install redis
-
- brew services start redis
-
- redis-server /usr/local/etc/redis.conf
- myKey是你的key值,abc是具体的value值
-
-
- 设置键值对 set myKey abc
- 查看键值对 get myKey
1)注意,刚刚第3步打开的服务不能关闭,再次打开一个cmd弹框
2)输入 redis-cli.exe -h 127.0.0.1 -p 6379 ,如果出现其他报错,不要着急,
3)更换命令输入 .\redis-cli.exe -h 127.0.0.1 -p 6379 ,看到下面的这个服务,就表示成功了
4)输入我们的设置命令,然后回车
set demo 123456
5)获取我们刚设置的缓存内容,注意,我们没有设置果abc,所以拿到的是(nil),我们设置了demo,就可以看到具体内容
get abc
npm i egg-redis -S
- exports.redis = {
- enable: true,
- package: 'egg-redis'
- }
- config.redis = {
- client: {
- port: 6379,
- host: '127.0.0.1',
- password: 'auth',
- db: 0
- },
- }
- const Service = require('egg').Service;
- const time = 60 * 60 * 24 * 365 //默认缓存失效时间 365天
- class RedisService extends Service {
- // 设置
- async set(key, value, seconds) {
- // seconds 有效时长
- let { redis } = this.app;
- value = JSON.stringify(value);
- if(!seconds){
- // await redis.set(key, value);
- await redis.set(key, value, 'EX', time);
- }else{
- // 设置有效时间
- await redis.set(key, value, 'EX', seconds);
- }
- }
- // 获取
- async get(key) {
- let { redis } = this.app;
- let data = await redis.get(key);
- if (!data) return;
- data = JSON.parse(data);
- return data;
- }
- // 清空redis
- async flushall() {
- let { redis } = this.app;
- redis.flushall();
- return;
- }
- }
- module.exports = RedisService;
(1)获取
let xiaoshuo = await this.app.redis.get('xiaoshuo1');
(2)设置
- let str = 123
- await this.app.redis.set('xiaoshuo1', str);
- async getXiaoshuo1() {
- let xiaoshuo = await this.app.redis.get('xiaoshuo1');
- //如果有缓存数据,就直接使用缓存
- if(xiaoshuo){
- this.ctx.body = {
- code:200,
- masg:'success',
- data: {
- list:xiaoshuo
- }
- }
- return
- }
- //获取mysql数据
- let allList = await this.app.mysql.query(initSql);
- this.ctx.body = {
- code:200,
- masg:'success',
- data: {
- list:allList
- }
- };
-
- }
- console.time() // 开始计时
-
- let goodsList = await this.service.redis.get('goodsList');
- if (!goodsList) {
- console.log('没有redis缓存')
- goodsList = await this.app.mysql.select('goods');
- this.service.redis.set('goodsList', goodsList);
-
- }
-
- console.timeEnd() // 打印时长
- await this.ctx.body = goodsList;