docker --- > 使用docker-compose.yml生成redis,并连接redis-cli

docker.compose.yml

  • 配置
version: '3.1'
services:
  redis:
    image: redis
    ports:
      - 6379:6379
  • 命令行:docker-compose up
    在这里插入图片描述
  • 查看: docker ps
    在这里插入图片描述
  • 进入redis-cli,输入以下
    docker exec -it 7dc0a redis-cli -h localhost -p 6379
    在这里插入图片描述

操作Redis数据

  • 设置 name=marron
    set name marron
    在这里插入图片描述
  • 获取name
    get name
    在这里插入图片描述

使用node连接redis,并进行数据的存储

  • 若docker未开启redis,会提示如下
    在这里插入图片描述
  • 连接redis
const redis = require('redis');
const client = redis.createClient(6379, '127.0.0.1');
client.on('error', async (err) => {
    console.log(`[Error]: ${err}`);
})
  • node中一些常用的redis操作
client.set('name', 'marron', redis.print);
client.get('name', async (err, value) => {
    if (err) throw err;
    console.log('Name: ' + value);
});

// 以下等价于 `client.hmset('marron', 'item', 'koaDemo', 'chapter', 'redisDemo')`
// 存储对象
client.hmset('marron', {
    'item': 'koaDemo',
    'chapter': 'redisDemo'
});

// 取出一个对象
client.hgetall('marron', async (err, obj) => {
    console.log(obj);
});

// 获取key
client.hkeys('marron', async (err, replies) => {
    replies.forEach((reply, i) => {
        console.log(i + ":" + reply);
    });
})

// 用List存储数据
client.lpush('marron1', 'koa', redis.print)
client.lpush('marron1', 'redisDemo', redis.print);
client.lrange('marron1', 0, -1, async (err, items) => {
    if (err) throw err;
    items.forEach(async (item, i) => {
        console.log(item);
    })
})
发布了177 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/piano9425/article/details/103333444