• Redis实操详解



    你来人间一趟,你要看看太阳


    在这里插入图片描述


    一、介绍

    Redis是一个基于内存的key-value结构数据库。Redis 是互联网技术领域使用最为广泛的存储中间件,它是「Remote Dictionary Service」的首字母缩写,也就是「远程字典服务」。

    • 基于内存存储,读写性能高
    • 适合存储热点数据(热点商品、资讯、新闻)
    • 企业应用广泛

    1. 概述

    Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. 翻译为:Redis是一个开源的内存中的数据结构存储系统,它可以用作:数据库、缓存和消息中间件。

    官网: https://redis.io

    在这里插入图片描述


    2. 非关系型数据库

    Redis是用C语言开发的一个开源的高性能键值对(key-value)数据库,官方提供的数据是可以达到100000+的QPS(每秒内查询次数)。它存储的value类型比较丰富,也被称为结构化的NoSql数据库。

    NoSql(Not Only SQL),不仅仅是SQL,泛指非关系型数据库。NoSql数据库并不是要取代关系型数据库,而是关系型数据库的补充

    • 关系型数据库(RDBMS):
      • Mysql
      • Oracle
      • DB2
      • SQLServer
    • 非关系型数据库(NoSql):
      • Redis
      • Mongo db
      • MemCached

    2. 安装

    Redis安装包分为windows版和Linux版:

    在这里插入图片描述

    # 1、将Redis安装包上传到Linux
    # 2、解压安装包
    tar -zxvf redis-4.0.0.tar.gz -C /usr/local==
    # 3、安装Redis的依赖环境gcc
    yum install gcc-c++==
    # 4、进入/usr/local/redis-4.0.0,进行编译
    make
    # 5、进入redis的src目录进行安装
    make install
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    3. 服务启动与停止

    # 执行Redis服务启动脚本文件
    ./redis-server
    # 停止Redis服务
    # Ctrl + C
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    4. 配置文件

    默认情况下Redis启动后是在前台运行,而且客户端不需要密码就可以连接到Redis服务。可以通过修改配置文件,实现Redis服务启动后是在后台运行,同时客户端认证通过后才能连接到Redis服务

    • Linux系统中Redis配置文件: REDIS_HOME/redis.conf
    • Windows系统中Redis配置文件: REDIS_HOME/redis.windows.conf

    # 修改配置文件
    vim redis.conf
    # 搜索关键词
    /dae
    # 设置Redis服务后台运行
    daemonize=no -> daemonize=yes
    # 搜索关键词
    /foob
    # 设置Redis服务密码(设置密码为:123456)
    #requirepass foobared -> requirepass 123456
    # 搜索关键词
    /bind
    # 设置允许客户端远程连接Redis服务
    bind 127.0.0.1 -> #bind 127.0.0.1
    
    # 重启Redis服务配置才能生效
    
    # 进入Redis安装目录
    cd /usr/local/redis-4.0.0
    # 启动Redis服务,指定使用的配置文件
    ./src/redis-server ./redis.conf
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    备注:

    Redis配置文件中的配置项前面不能有空格,需要顶格写
    daemonize: 用来指定redis是否要用守护线程的方式启动,设置成yes时,代表开启守护进程模式。在该模式下,redis会在后台运行
    requirepass: 设置Redis的连接密码
    bind: 如果指定了bind,则说明只允许来自指定网卡的Redis请求。如果没有指定,就说明可以接受来自任意一个网卡的Redis请求。





    二、数据类型

    Redis存储的是key-value结构的数据,其中key是字符串类型,value有5种常用的数据类型:

    • 字符串 string: 普通字符串,常用
    • 哈希 hash: 适合存储对象
    • 列表 list: 按照插入顺序排序,可以有重复元素
    • 集合 set: 无序集合,没有重复元素
    • 有序集合 sorted set / zset: 集合中每个元素关联一个分数(score),根据分数升序排序,没有重复元素

    在这里插入图片描述





    三、使用命令

    更多命令可以参考Redis中文网:https://www.redis.net.cn

    在这里插入图片描述


    1. 字符串string

    set key value
    # 设置指定key的值
    get key
    # 获取指定key的值
    setex key seconds value
    # 设置指定key的值,并将 key 的过期时间设为 seconds 秒
    setnx key value
    # 只有在 key 不存在时设置 key 的值
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2. 哈希hash

    Redis hash 是一个string类型的 fieldvalue 的映射表,hash特别适合用于存储对象
    在这里插入图片描述

    hset key field value
    # 将哈希表 key 中的字段 field 的值设为 value
    hget key field   
    # 获取存储在哈希表中指定字段的值
    hdel key field   
    # 删除存储在哈希表中的指定字段
    hkeys key
    # 获取哈希表中所有字段
    hvals key
    # 获取哈希表中所有值
    hgetall key
    # 获取在哈希表中指定 key 的所有字段和值
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    3. 列表list

    Redis list 是简单的字符串列表,按照插入顺序排序
    在这里插入图片描述

    lpush key value1 [value2]
    # 将一个或多个值插入到列表头部
    lrange key start stop  
    # 获取列表指定范围内的元素
    rpop key 
    # 移除并获取列表最后一个元素
    llen key
    # 获取列表长度
    brpop key1 [key2 ] timeout
    # 移出并获取列表的最后一个元素, 如果列表没有元素会阻塞列表直到等待超    时或发现可弹出元素为止
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    4. 集合set

    Redis setstring 类型的无序集合。集合成员是唯一的,这就意味着集合中不能出现重复的数据
    在这里插入图片描述

    sadd key member1 [member2]  
    # 向集合添加一个或多个成员
    smembers key 
    # 返回集合中的所有成员
    scard key
    # 获取集合的成员数
    sinter key1 [key2]
    # 返回给定所有集合的交集
    sunion key1 [key2] 
    # 返回所有给定集合的并集
    sdiff key1 [key2]
    # 返回给定所有集合的差集
    srem key member1 [member2]
    # 移除集合中一个或多个成员
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    5. 有序集合sorted set

    Redis sorted set 有序集合是 string 类型元素的集合,且不允许重复的成员。每个元素都会关联一个double类型的分数(score) 。redis正是通过分数来为集合中的成员进行从小到大排序。有序集合的成员是唯一的,但分数却可以重复
    在这里插入图片描述

    zadd key score1 member1 [score2 member2]
    # 向有序集合添加一个或多个成员,或者更新已存在成员的 分数
    zrange key start stop [WITHSCORES]
    # 通过索引区间返回有序集合中指定区间内的成员
    zincrby key increment member 
    # 有序集合中对指定成员的分数加上增量 increment
    zrem key member [member ...]
    # 移除有序集合中的一个或多个成员
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    6. 通用命令(key)

    Redis中的通用命令,主要是针对 key 进行操作的相关命令:

    keys pattern
    # 查找所有符合给定模式( pattern)的 key 
    exists key
    # 检查给定 key 是否存在
    type key
    # 返回 key 所储存的值的类型
    ttl key
    # 返回给定 key 的剩余生存时间(TTL, time to live),以秒为单位
    del key
    # 该命令用于在 key 存在是删除 key
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10




    四、实操(Java)

    1. 分类

    在java程序中操作Redis就需要使用Redis的Java客户端,就如同我们使用JDBC操作MySQL数据库一样。Redis 的 Java 客户端很多,官方推荐的有三种:

    • Jedis(推荐)
    • Lettuce
    • Redisson

    Spring 对 Redis 客户端进行了整合,提供了 Spring Data Redis,在Spring Boot项目中还提供了对应的Starter,即 spring-boot-starter-data-redis



    2. Jedis

    Jedis 是 Redis 的 Java 版本的客户端实现。

    maven坐标:

    <dependency>
    	<groupId>redis.clientsgroupId>
    	<artifactId>jedisartifactId>
    	<version>2.8.0version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    使用 Jedis 操作 Redis 的步骤: 获取连接 => 执行操作 => 关闭连接

    示例代码:

    package com.itheima.test;
    
    import org.junit.Test;
    import redis.clients.jedis.Jedis;
    import java.util.Set;
    
    /**
     * 使用Jedis操作Redis
     */
    public class JedisTest {
    
        @Test
        public void testRedis(){
            //1 获取连接
            Jedis jedis = new Jedis("localhost",6379);
            
            //2 执行具体的操作
            jedis.set("username","xiaoming");
    
            String value = jedis.get("username");
            System.out.println(value);
    
            //jedis.del("username");
    
            jedis.hset("myhash","addr","bj");
            String hValue = jedis.hget("myhash", "addr");
            System.out.println(hValue);
    
            Set<String> keys = jedis.keys("*");
            for (String key : keys) {
                System.out.println(key);
            }
    
            //3 关闭连接
            jedis.close();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37


    3. Spring Data Redis

    Spring Data RedisSpring 的一部分,提供了在 Spring 应用中通过简单的配置就可以访问 Redis 服务,对 Redis 底层开发包进行了高度封装。在 Spring 项目中,可以使用 Spring Data Redis来简化 Redis 操作。

    网址:https://spring.io/projects/spring-data-redis

    在这里插入图片描述

    maven坐标:

    <dependency>
    	<groupId>org.springframework.datagroupId>
    	<artifactId>spring-data-redisartifactId>
    	<version>2.4.8version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Spring Boot提供了对应的 Startermaven坐标:

    <dependency>
    	<groupId>org.springframework.bootgroupId>
    	<artifactId>spring-boot-starter-data-redisartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4

    Spring Data Redis 中提供了一个高度封装的类:RedisTemplate,针对 Jedis 客户端中大量api进行了归类封装,将同一类型操作封装为operation接口,具体分类如下:

    • ValueOperations: 简单K-V操作
    • SetOperations: set类型数据操作
    • ZSetOperations: zset类型数据操作
    • HashOperations: 针对hash类型的数据操作
    • ListOperations: 针对list类型的数据操作


    4. 使用方式

    ⑴. 环境搭建

    创建maven项目springdataredis_demo,配置 pom.xml 文件:

    
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0modelVersion>
        <parent>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-parentartifactId>
            <version>2.4.5version>
            <relativePath/>
        parent>
        <groupId>com.itheimagroupId>
        <artifactId>springdataredis_demoartifactId>
        <version>1.0-SNAPSHOTversion>
        <properties>
            <java.version>1.8java.version>
        properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <scope>testscope>
            dependency>
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-data-redisartifactId>
            dependency>
        dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-maven-pluginartifactId>
                    <version>2.4.5version>
                plugin>
            plugins>
        build>
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    ⑵. 编写启动类
    package com.itheima;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class App {
    
        public static void main(String[] args) {
            SpringApplication.run(App.class,args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    ⑶. 配置application.yml
    spring:
      application:
        name: springdataredis_demo
      #Redis相关配置
      redis:
        host: localhost
        port: 6379
        #password: 123456
        database: 0 #操作的是0号数据库
        jedis:
          #Redis连接池配置
          pool:
            max-active: 8 #最大连接数
            max-wait: 1ms #连接池最大阻塞等待时间
            max-idle: 4 #连接池中的最大空闲连接
            min-idle: 0 #连接池中的最小空闲连接
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    spring.redis.database: 指定使用Redis的哪个数据库,Redis服务启动后默认有16个数据库,编号分别是从0到15。
    可以通过修改Redis配置文件来指定数据库的数量。


    ⑷. 提供配置类
    package com.itheima.config;
    
    import org.springframework.cache.annotation.CachingConfigurerSupport;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    /**
     * Redis配置类
     */
    @Configuration
    public class RedisConfig extends CachingConfigurerSupport {
    
        @Bean
        public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
    
            RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
    
            //默认的Key序列化器为:JdkSerializationRedisSerializer
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    
            redisTemplate.setConnectionFactory(connectionFactory);
    
            return redisTemplate;
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    当前配置类不是必须的,因为 Spring Boot 框架会自动装配 RedisTemplate 对象,但是默认的key序列化器为JdkSerializationRedisSerializer,导致我们存到Redis中后的数据和原始数据有差别


    ⑸. 提供测试类
    package com.itheima.test;
    
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    @SpringBootTest
    @RunWith(SpringRunner.class)
    public class SpringDataRedisTest {
    
        @Autowired
        private RedisTemplate redisTemplate;
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15


    5. 操作数据

    ⑴. 字符串类型数据
    /**
     * 操作String类型数据
    */
    @Test
    public void testString(){
        //存值
        redisTemplate.opsForValue().set("city123","beijing");
    
        //取值
        String value = (String) redisTemplate.opsForValue().get("city123");
        System.out.println(value);
    
        //存值,同时设置过期时间
        redisTemplate.opsForValue().set("key1","value1",10l, TimeUnit.SECONDS);
    
        //存值,如果存在则不执行任何操作
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("city1234", "nanjing");
        System.out.println(aBoolean);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    ⑵. 哈希类型数据
    /**
     * 操作Hash类型数据
    */
    @Test
    public void testHash(){
        HashOperations hashOperations = redisTemplate.opsForHash();
    
        //存值
        hashOperations.put("002","name","xiaoming");
        hashOperations.put("002","age","20");
        hashOperations.put("002","address","bj");
    
        //取值
        String age = (String) hashOperations.get("002", "age");
        System.out.println(age);
    
        //获得hash结构中的所有字段
        Set keys = hashOperations.keys("002");
        for (Object key : keys) {
            System.out.println(key);
        }
    
        //获得hash结构中的所有值
        List values = hashOperations.values("002");
        for (Object value : values) {
            System.out.println(value);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    ⑶. 列表类型数据
    /**
     * 操作List类型的数据
    */
    @Test
    public void testList(){
        ListOperations listOperations = redisTemplate.opsForList();
    
        //存值
        listOperations.leftPush("mylist","a");
        listOperations.leftPushAll("mylist","b","c","d");
    
        //取值
        List<String> mylist = listOperations.range("mylist", 0, -1);
        for (String value : mylist) {
            System.out.println(value);
        }
    
        //获得列表长度 llen
        Long size = listOperations.size("mylist");
        int lSize = size.intValue();
        for (int i = 0; i < lSize; i++) {
            //出队列
            String element = (String) listOperations.rightPop("mylist");
            System.out.println(element);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    ⑷. 集合类型数据
    /**
     * 操作Set类型的数据
    */
    @Test
    public void testSet(){
        SetOperations setOperations = redisTemplate.opsForSet();
    
        //存值
        setOperations.add("myset","a","b","c","a");
    
        //取值
        Set<String> myset = setOperations.members("myset");
        for (String o : myset) {
            System.out.println(o);
        }
    
        //删除成员
        setOperations.remove("myset","a","b");
    
        //取值
        myset = setOperations.members("myset");
        for (String o : myset) {
            System.out.println(o);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    ⑸. 有序集合类型数据
    /**
     * 操作ZSet类型的数据
    */
    @Test
    public void testZset(){
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
    
        //存值
        zSetOperations.add("myZset","a",10.0);
        zSetOperations.add("myZset","b",11.0);
        zSetOperations.add("myZset","c",12.0);
        zSetOperations.add("myZset","a",13.0);
    
        //取值
        Set<String> myZset = zSetOperations.range("myZset", 0, -1);
        for (String s : myZset) {
            System.out.println(s);
        }
    
        //修改分数
        zSetOperations.incrementScore("myZset","b",20.0);
    
        //取值
        myZset = zSetOperations.range("myZset", 0, -1);
        for (String s : myZset) {
            System.out.println(s);
        }
    
        //删除成员
        zSetOperations.remove("myZset","a","b");
    
        //取值
        myZset = zSetOperations.range("myZset", 0, -1);
        for (String s : myZset) {
            System.out.println(s);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    ⑹. 通用操作
    /**
     * 通用操作,针对不同的数据类型都可以操作
    */
    @Test
    public void testCommon(){
        //获取Redis中所有的key
        Set<String> keys = redisTemplate.keys("*");
        for (String key : keys) {
            System.out.println(key);
        }
    
        //判断某个key是否存在
        Boolean itcast = redisTemplate.hasKey("itcast");
        System.out.println(itcast);
    
        //删除指定key
        redisTemplate.delete("myZset");
    
        //获取指定key对应的value的数据类型
        DataType dataType = redisTemplate.type("myset");
        System.out.println(dataType.name());
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
  • 相关阅读:
    Linux一篇入门(以Ubuntu为例)
    使用贪心来解决的一些问题
    Java 设计模式系列:解释器模式
    【电商】电商后台设计—电商订单
    08-vue-cli 本地存储
    SCI写作指南
    「SpringBoot」07 指标监控
    WPF 控件小技巧记录(持续更新)
    微信整合CRM系统的好处
    Python 递归函数打印斐波那契数列
  • 原文地址:https://blog.csdn.net/weixin_45137565/article/details/126690699