跳至主要內容

Redis

Yang大约 4 分钟

是 Key-Value 型 NoSQL 数据库

  • 将数据存储在内存中,同时也能持久化到磁盘

  • 常用与缓存,利用内存的高效提高程序的处理速度

特点

  • 速度快
  • 广泛的语言支持
  • 持久化
    • RDB:全量备份
    • AOF:日志更新
  • 支持多种数据结构
  • 主从复制:多台 Redis 数据库保持同步
  • 分布式与高可用

安装

# 如果没有 gcc 则需提前安装
$ wget https://download.redis.io/releases/redis-5.0.2.tar.gz
$ tar xzf redis-6.2.5.tar.gz
$ cd redis-6.2.5
$ make

# 启动
[root@user redis-5.0.2]# ./src/redis-server redis.conf

配置

配置项示例说明
daemonizedaemonize yes是否启用后台运行,默认 no
portport 6379设置端口号,默认 6379
logfilelogfile 日志文件设置日志文件
databasesdatabases 255设置 redis 数据库总量
dirdir 数据文件目录设置数据文件存储目录(./dumo.rdb
requirepassrequirepass 12345设置使用密码

命令

./src/redis-cli:进入内置命令模式

  • ./src/redis-cli shutdown:关闭 redis
  • -p 6380:设置进入内置命令模式的端口号
  • ping:返回 PONG 表示 redis 正常启动
  • exit:退出内置命令模式
  • select 0(数据库索引)
  • auth 密码:设置密码后,进入内置命令模式后必须先使用该命令验证密码后才可进行命令操作
命令示例说明
selectselect 0选择 0 号数据库
getget hello获得 key=hello 的结果
setset name lily设置 key=name,value=lily
keyskeys he*根据 Pattern 表达式查询符合条件的 key
dbsizedbsize返回 key 的总数
existsexists a检查 key=a 是否存在
deldel a删除 key=a 的数据
expireexpire hello 20设置 key=hello 20 秒后过期
ttlttl hello查看 key=a 的过期剩余时间

数据类型

String

字符串类型

  • 最大 512M,建议单个字符串长度不要超过 100K
命令示例说明
getget hello获得 key=value 结果
setset hello world设置 key=hello,value=hello
mgetmget hello java一次性获取多个值
msetmset hello world java best一次性设置多个值
deldel hello删除 key=hello
incrincr countKey 值自增 1
decrdecr countkey 值自减 1
incrbyincrby count 99指定自增步长
decrbydecrby count 99指定自减步长

Hash

键值对类型:用于存储结构化数据

命令示例说明
hgethget emp:1 age获取 hash 中 key=age 的值
hsethset emp:1 age 23设置 hash 中 age=23
hmgethmget emp:1 age name获取 hash 多个值
hmsethmset emp:1 age 28 name kaka设置 hash 多个值
hgetallhgetall emp:1获取 hash 所有键值
hdelhdel emp:1 age删除 emp:1 的 age
hexistshexists emp:1 name检查是否存在
hlenhlen emp:1获取长度(键值对个数)

List

列表类型

  • 一系列字符串的数组,安插入顺序排序

  • 最大长度为 2 的 32 次方减 1,可以包含 40 亿 个元素

命令说明
rpush listkey c b a列表右侧依次插入元素
lpush listkey f e d列表左侧依次插入元素
rpop list列表右侧弹出元素
lpop list列表左侧弹出元素
lrange list 0 -1显示 key 列表所有元素

Set

是字符串的 无序 集合,集合成员是 唯一

  • sadd set1 a:设置元素
  • sadd set1 b:设置元素
  • smembers set1:显示所有元素
  • sinter set1 set2:显示交集元素
  • sunion set1 set2:显示并集元素
  • sdiff set1 set2:显示差集元素

Zset

是字符串的 有序 集合,集合成员是 唯一

  • zadd zset1 100 a:设置元素
  • zadd zset1 101 b:设置元素
  • zrange zset1 0 -1 [withscores]:显示所有元素[打印份数]
  • zrangebyscore zset1 100 103:显示分数范围内的元素(闭区间)

Jedis

语法

package com.imooc.jedis;

import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JedisTestor {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.132.144" , 6379);
        try {
            jedis.auth("12345");
            jedis.select(2);
            System.out.println("Redis连接成功");

            //字符串
            jedis.set("sn" , "7781-9938");
            String sn = jedis.get("sn");
            System.out.println(sn);
            jedis.mset(new String[]{"title" , "婴幼儿奶粉" , "num" , "20"});
            List<String> goods =  jedis.mget(new String[]{"sn" , "title" , "num"});
            System.out.println(goods);
            Long num = jedis.incr("num");
            System.out.println(num);

            //Hash
            jedis.hset("student:3312" , "name" , "张晓明");
            String name = jedis.hget("student:3312" , "name");
            System.out.println(name);
            Map<String,String> studentMap = new HashMap();
            studentMap.put("name", "李兰");
            studentMap.put("age", "18");
            studentMap.put("id", "3313");
            jedis.hmset("student:3313", studentMap);
            Map<String,String> smap =  jedis.hgetAll("student:3313");
            System.out.println(smap);

            //List
            jedis.del("letter");
            jedis.rpush("letter" , new String[]{"d" , "e" , "f"});
            jedis.lpush("letter" ,  new String[]{"c" , "b" , "a"});
            List<String> letter =  jedis.lrange("letter" , 0 , -1);
            jedis.lpop("letter");
            jedis.rpop("letter");
            letter = jedis.lrange("letter", 0, -1);
            System.out.println(letter);
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }
    }
}

示例

package com.imooc.jedis;

import com.alibaba.fastjson.JSON;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CacheSample {
    public CacheSample(){
        Jedis jedis = new Jedis("10.211.55.5");
        try {
            List<Goods> goodsList = new ArrayList<Goods>();
            goodsList.add(new Goods(8818, "红富士苹果", "", 3.6f));
            goodsList.add(new Goods(8819, "进口脐橙", "", 5f));
            goodsList.add(new Goods(8820, "进口香蕉", "", 25f));
            jedis.auth("12345");
            jedis.select(3);
            for (Goods goods : goodsList) {
                String json = JSON.toJSONString(goods);
                System.out.println(json);
                String key = "goods:" + goods.getGoodsId();
                jedis.set(key , json);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            jedis.close();
        }
    }

    public static void main(String[] args) {
        new CacheSample();

        System.out.printf("请输入要查询的商品编号:");
        String goodsId = new Scanner(System.in).next();
        Jedis jedis = new Jedis("10.211.55.5");
        try{
            jedis.auth("12345");
            jedis.select(3);
            String key = "goods:" + goodsId;
            if(jedis.exists(key)){
                String json = jedis.get(key);
                System.out.println(json);
                Goods g = JSON.parseObject(json, Goods.class);
                System.out.println(g.getGoodsName());
                System.out.println(g.getPrice());
            }else{
                System.out.println("您输入的商品编号不存在,请重新输入!");
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();
        }
    }
}
package com.imooc.jedis;

public class Goods {
    private Integer goodsId;
    private String goodsName;
    private String description;
    private Float price;

    public Goods(){

    }

    public Goods(Integer goodsId, String goodsName, String description, Float price) {
        this.goodsId = goodsId;
        this.goodsName = goodsName;
        this.description = description;
        this.price = price;
    }

    public Integer getGoodsId() {
        return goodsId;
    }

    public void setGoodsId(Integer goodsId) {
        this.goodsId = goodsId;
    }

    public String getGoodsName() {
        return goodsName;
    }

    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }
}
上次编辑于:
贡献者: sunzhenyang