1
0

redis使用笔记

2026-05-12
2026-05-12

一、常用命令记录

一、基础命令

redis中有默认的十六个数据库

  1. 切换数据库 select 索引 [0-15] 默认是选择0索引数据库

  2. dbsize 查看key的个数

  3. flushdb 清空当前索引数据库中的数据

  4. flushall 清空所有数据库 16个库全删(删的是数据)

通用语法

del key 根据key删除

keys * 查看所有key

type key 查询key的类型,根据类型 就可以使用不同的api

ttl key 查看key的有效时间 -1 永不超时. -2 没有这个数据或者这个数据已经过时了. 正数: 还有多少秒过期

expire key s 设置数据的过期时间 单位秒 例如:expire name 20 表示key为name的缓存20秒后过期 男

存入 set key value

取出 get key value

移除 语法:del key

1.2、hash类型

hset key filed value 存入一个字段,一个值

hmset key field value field value 存入多个字段多个值

hget key filed

hdel key flied

hgetall key

1.3、list类型

语法:lpush key value value value 左添加

rpush key value value value 右添加

语法:lrange key startIndex endIndex

移除 语法:lpop key : 左弹

rpop key : 右弹

1.4、set类型

存入语法:sadd key value value value ...

获取 语法:smembers  key

### 移除

语法:srem key  value value 

### 特点:

​	和list基本一致。唯一区别就是它不能重复

1.5、sorted set类型

### 存入

语法:zadd key  socre value  socre value  socre value


### 取出

语法: zscore key 值    获得指定成员的分数  

zrange key start(索引) end(索引)   

升序查询数据 [withscores]  []表示可有可无


### 	          reverse 反转

语法:zrevrange  key start  end  [withscores]  降序查询数据


### 删除

语法:zrem key 值 删除指定的成员


### 特点:

在set的基础上进行了一定的增强,有序不重复 , 顺序的定义(给每一个值匹配一个对应的分数概念-就是数字,排序条件)

java操作redis

## SpringDataRedis

 `前置说明`
>
> Spring Data Redis是Spring的一部分,对Redis底层开发包进行了高度封装,提供了一个高度封装的类:**RedisTemplate**,用于操作各种数据类型。
>
> - ValueOperations:简单K-V操作
> - SetOperations:    set类型数据操作
> - ZSetOperations:  zset类型数据操作
> - HashOperations: 针对hash类型的数据操作
> - ListOperations:    针对list类型的数据操作
 	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.4.5</version>
            </plugin>
        </plugins>
    </build>
spring:
  application:
    name: redis_demo
  redis:
    host: localhost
    port: 6379
    database: 0 # 操作的是0号数据库
    jedis: #Redis连接池配置
      pool:
        max-active: 8 #最大连接数
        max-wait: 1ms #连接池最大阻塞等待时间
        max-idle: 4 #连接池中的最大空闲连接
        min-idle: 0 #连接池中的最小空闲连接


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RedisApplication {
    public static void main(String[] args) {
        SpringApplication.run(RedisApplication.class, args);
    }
}

//Redis配置类
//当前配置类不是必须的,因为 Spring Boot 框架会自动装配 RedisTemplate 对象,
//但是默认的key序列化器为JdkSerializationRedisSerializer,导致我们存到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());

        //设置value的序列化器   默认是JdkSerializationRedisSerializer
        //redisTemplate.setValueSerializer(new StringRedisSerializer());
        //redisTemplate.setHashValueSerializer(new StringRedisSerializer());

        redisTemplate.setConnectionFactory(connectionFactory);

        return redisTemplate;
    }
}
/**
     * 测试String类型的数据
     */
    @Test
    public void testString(){
        //1.string类型的操作对象
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //2.存入数据
        //valueOperations.set("redisOperations","SpringDataRedis");
        //3.获取数据
        //Object redisOperations = valueOperations.get("redisOperations");

        //4.设置过期时间
        //valueOperations.set("code","123456",5, TimeUnit.MINUTES);
        //5 如果存入数据时,该key已经存在了,就不保存,如果不存在,就存入。
        valueOperations.setIfAbsent("redisOperations","SpringDataRedis");

        Object redisOperations = valueOperations.get("redisOperations");
        System.out.println(redisOperations);
    }
/**
     * 测试列表类型
     */
    @Test
    public void testList(){
        //1.获取列表的操作的对象
        ListOperations ops = redisTemplate.opsForList();
        //2.存值
        //ops.leftPush("names","张三");
        //ops.leftPushAll("names","李四","老王","test","qf2303");// "qf2303"  "test"  "老王"   "李四"  "张三"
        //3.取值
        //获取list中的元素个数
//        Long size = ops.size("names");
//        System.out.println(size);

        //获取指定位置的元素
        //List names = ops.range("names", 0, 4);
        //System.out.println(names);
//        for (Object name : names) {
//            System.out.println(name);
//        }

        //注意:他和list类型的命令有差别
        //List names2 = ops.range("names", 0, -1);
        //System.out.println(names2);


        //移除操作
        Object popName = ops.rightPop("names");
        System.out.println(popName);
    }
 /**
     * 测试set类型的数据
     */
    @Test
    public void testSet(){
        //1.获取set类型的操作对象
        SetOperations ops = redisTemplate.opsForSet();

        //2.存入数据
        //ops.add("address","北京","天津","上海","石家庄","南京");

        //3.获取集合中的数量
        //Long size = ops.size("address");
        //System.out.println(size);

        //4.取出set中的每一个元素
//        Set address = ops.members("address");
//        for (Object o : address) {
//            System.out.println(o);
//        }

        //5.移除元素
        //Long remove = ops.remove("address", "石家庄");
        //System.out.println(remove);

        //准备两个set
//        ops.add("s1","a","b","c","d");
//        ops.add("s2","a","b","c","e");

        //取两个集合的交集
        Set set = ops.intersect("s1", "s2");
        for (Object o : set) {
            System.out.println(o);
        }
        System.out.println("---------以上是两个集合交集-------------");

        //取两个集合的并集
        Set union = ops.union("s1", "s2");
        for (Object o : union) {
            System.out.println(o);
        }
        System.out.println("---------以上是两个集合并集-------------");

        //取两个集合的差集
        Set difference = ops.difference( "s2","s1");
        for (Object o : difference) {
            System.out.println(o);
        }
        System.out.println("---------以上是两个集合差集-------------");
    }
 /**
     * 测试Sorted Set类型
     */
    @Test
    public void testZSet(){
        //1.获取操作对象
        ZSetOperations ops = redisTemplate.opsForZSet();
        //2.存值
        //ops.add("category","book",10);
        //ops.add("category","phone",80);
        //ops.add("category","digital",70);

        //3.取出元素的个数
//        Long size = ops.size("category");
//        System.out.println(size);

        //4.取出元素
//        Set categories = ops.range("category", 0, 2);
//        for (Object category : categories) {
//            System.out.println(category);
//        }


        //6.移除元素
        Long remove = ops.remove("category", "book");
        System.out.println(remove);

        //5.倒序获取
        Set categories = ops.reverseRange("category",0,2);
        for (Object category : categories) {
            System.out.println(category);
        }
    }

评论