Redis之入门学习

Redis入门知识

Redis介绍
  • Redis是Key-Value型NoSQL数据库
    Redis将数据存储在内存中,同时也能持久化到磁盘
    Redis常用于缓存,利用内存的高效提高程序的处理速度
Redis的安装与启动
  • 在Linux环境中:
  • 在/usr/local/中添加redis文件夹, 安装gcc工具: cd /usr/local/ mkdir redis yum install gcc
  • 下载redis安装包: wget https://github.com/redis/redis/archive/7.0.4.tar.gz
  • 解压redis压缩包: tar xzf 7.0.4.tar.gz
  • 进入解压完的redis文件夹,并使用make命令进行安装: tar xzf 7.0.4.tar.gz make
  • 启动redis服务器: ./src/redis-server redis.conf (需要防火墙开放6379端口,否则会报“Failed listening on port 6379 (TCP), aborting.”错误)
Redis的常用基本配置
  • daemonize: [案例]daemonize yes [说明]是否启用后台运行,默认no
    port: [案例]port 6379 [说明]设置端口号,默认6379
    logfile: [案例]logfile日志文件 [说明]设置日志文件
    databases: [案例]databases 255 [说明]设置redis数据库总量
    dir: [案例]dir 数据文件目录 [说明]设置数据文件存储目录
    requirepass: [案例]requirepass 12345 [说明]设置使用密码,登录时在redis客户端中使用auth 密码命令连接数据库
    修改Redis的配置:
    编辑redis.conf文件: vim redis.conf
    打开redis客户端: ./src/redis-cli -p 6379
    关闭redis服务: ./src/redis-cli shutdown
Redis通用命令
  • select: [案例]select 0 [说明]选择0号数据库
    set: [案例]set name lily [说明]设置key=name,value=lily
    get: [案例]get hello [说明]获得key=hello结果
    keys: [案例]keys he* [说明]根据Pattern表达式查询符合条件的Key
    dbsize: [案例]dbsize [说明]返回key的总数
    exists: [案例]exists a [说明]检查key=a是否存在
    del: [案例]del [说明]a删除key=a的数据
    expire: [案例]expire hello 20 [说明]设置key=hello 20秒后过期
    ttl: [案例]ttl hello [说明]查看key=a的过期剩余时间
Redis数据类型
  • String字符串类型:
    常用命令:
    get: [案例]get hello [说明]获得key=hello结果
    set: [案例]set hello world [说明]设置key=hello,value=hello
    mset/mget: [案例]mset hello world java best mget hello java[说明]—次性设置或者获取多个值
    del: [案例]del hello [说明]删除key=hello
    incr/decr: [案例]incr count decr count [说明]key值自增/自减1
    incrby/decrby: [案例]incrby count 99 decrby count 99 [说明]自增自减指定步长
  • Hash键值类型:
    Hash类型用于存储结构化数据
    常用命令:
    hget: [案例]hget emp:1 age [说明]获取hash中key=age的值
    hset: [案例]hset emp:1 age 23 [说明]设置hash中age=23
    hmset/hmget/hgetall: [案例]hmset emp:1 age 30 name kaka hmget emp:1 age name hgetall emp:1 [说明]设置hash多个值 获取hash多个值 获取hash所有值
    hdel: [案例]hdel emp:1 age [说明]删除emp:1的age
    hexists: [案例]hexists emp:1 name [说明]检查是否存在
    hlen: [案例]hlen emp:1 [说明]获取指定长度
  • List列表类型:
    List列表就是一系列字符串的“数组”,按插入顺序排序
    List列表最大长度为2的32次方-1,可以包含40亿个元素
    常用命令:
    rpush: [案例]rpush listkey c b a [说明]右侧插入
    lpush: [案例]lpush listkey f e d [说明]左侧插入
    rpop: [案例]lpush listkey [说明]右侧弹出
    lpop: [案例]lpush listkey [说明]左侧弹出
    lrange: [案例]range list 0 -1 [说明]输出列表0到结尾的元素
  • Set与Zset集合类型:
    Set集合是字符串的无序集合,集合成员是唯一的
    Zset集合是字符串的有序集合,集合成员是唯一的
    sadd: [案例] sadd s1 a [说明] 向集合中添加元素
    smembers: [案例] smembers s1 [说明]输出集合中的元素
    sinter: [案例] sinter s1 s2 [说明]取两个集合的交集
    sunion: [案例] sunion s1 s2 [说明]取两个元素的并集
    sdiff: [案例] sdiff s1 s2 [说明]取集合一有的但集合二没有的元素
    zadd: [案例] zadd z1 100 a [说明]向集合中添加分数为100的元素
    zrange: [案例] zrange z1 0 -1 (withscores)[说明]输出集合中0到结尾的元素(带元素的分数)
    zrangebyscore: [案例] zrangescore z1 100 103 [说明]输出分数从100到103的元素
Jedis
  • Jedis是Java语言开发的Redis客户端工具包
    Jedis只是对Redis命令的封装,掌握Redis命令便可轻易上手
    注: 在使用远程连接时先在redis.conf中修改绑定的IP地址
Jedis安装
  • 在Maven中添加依赖即可
<dependencies>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>4.3.0-m1</version>
        </dependency>
    </dependencies>
  • Jedis简单方法测试
public class JedisTestor {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.144.128", 6379);
        try{
            // jedis.auth("123456"); 登录验证密码
        jedis.select(1);
        System.out.println("Redis连接成功");
            // 字符串
            jedis.set("sa", "Hello Redis");
            String sa = jedis.get("sa");
            System.out.println(sa);
            jedis.mset(new String[]{"name", "zhangsan", "gender", "male", "age", "15"});
            List<String> emp = jedis.mget(new String[]{"name", "gender", "age"});
            System.out.println(emp);
            long age = jedis.incr("age");
            System.out.println(age);
            // hash
            jedis.hset("student:038", "name", "张少灵");
            String name = jedis.hget("student:038", "name");
            System.out.println(name);
            HashMap<String, String> studentMap = new HashMap<>();
            studentMap.put("name", "李兰");
            studentMap.put("age", "18");
            studentMap.put("id", "039");
            jedis.hmset("student:039",studentMap);
            Map<String, String> smap = jedis.hgetAll("student:039");
            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();
        }
    }
}
  • Jedis保存对象与查询数据
<!-- 使用fastjson转换对象和字符串 -->
<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.12</version>
        </dependency>
// 对象类
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;
    }
}

//Jedis存储与查询类
public class CacheSample {
    public CacheSample(){
        Jedis jedis = new Jedis("192.168.144.128", 6379);
        try {
            List<Goods> goodsList = new ArrayList<>();
            goodsList.add(new Goods(8818, "红富士苹果", "", 3.5f));
            goodsList.add(new Goods(8819, "进口脐橙", "", 5f));
            goodsList.add(new Goods(8820, "进口香蕉", "", 25f));
            jedis.select(1);
            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();
        String goodsId = new Scanner(System.in).next();
        Jedis jedis = new Jedis("192.168.144.128", 6379);
        try{
            jedis.select(1);
            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();
        }
    }

}
Redis持久化策略
  • 1)RDB(数据快照模式),定期存储,保存的是数据本身,存储文件是紧凑的。当服务器启动的时候,可以从RDB文件中恢复数据集。
    2)AOF(追加模式),每次修改数据时,同步到硬盘(写操作日志),保存的是数据的变更记录。在服务器重新启动的时候,会把所有的写操作重新执行一遍,从而实现数据备份。当写操作集过大(比原有的数据集还大),Redis 会重写写操作集。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值