Spring Boot 中使用 Redis 基本数据类型

Spring Boot 中使用 Redis 基本数据类型

导入依赖

build.gradle 中添加 Redis 核心依赖和连接池依赖(Spring Boot 4.0.1 版本适配):

// Redis 核心依赖(Spring Data Redis 整合)
implementation 'org.springframework.boot:spring-boot-starter-data-redis:4.0.1'
// 连接池依赖(Apache Commons Pool2,用于 Lettuce 连接池管理)
implementation 'org.apache.commons:commons-pool2:2.13.1'

YML 配置 Redis 相关参数

application.yml 中配置 Redis 连接信息、连接池参数,默认端口 6379 可省略:

spring:
  data:
    redis:
      host: 192.168.10.158  # Redis 服务器地址
      port: 6379             # Redis 端口(默认6379,可省略)
      lettuce:               # 使用 Lettuce 客户端(Spring Boot 2.x+ 默认)
        pool:
          enabled: true      # 启用连接池
          max-active: 10     # 连接池最大活跃连接数
          max-idle: 10       # 连接池最大空闲连接数
          max-wait: 1000     # 连接池最大等待时间(毫秒)
          min-idle: 10       # 连接池最小空闲连接数

String 数据类型测试

String 是 Redis 最基础的数据类型,适用于存储字符串、数字等简单数据。Spring Boot 默认提供 StringRedisTemplate 用于操作数据。

测试代码

package com.springboot;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;

@SpringBootTest
public class StringTest {
    // Redis Key 前缀(统一命名空间,避免 Key 冲突)
    private static final String KEY_PREFIX = "com:springboot:";
    
    // 注入 StringRedisTemplate(默认装配,专门操作 String 类型)
    @Autowired
    private StringRedisTemplate template;
    
    @Test
    public void test() {
        // 1. 存储字符串数据(key: com:springboot:user:username:10,value: peppa)
        template.opsForValue().set(KEY_PREFIX + "user:username:10", "peppa");
        
        // 2. 获取字符串数据
        String username = template.opsForValue().get(KEY_PREFIX + "user:username:10");
        System.out.println("username:10 = " + username);
        
        // 3. 数字自增操作(支持整数、浮点数)
        template.opsForValue().set(KEY_PREFIX + "counter", "0"); // 初始化计数器为 0
        template.boundValueOps(KEY_PREFIX + "counter").increment(); // 自增 1(对应 Redis incr 命令)
        template.boundValueOps(KEY_PREFIX + "counter").increment(5); // 自增 5(对应 Redis incrby 命令)
        template.boundValueOps(KEY_PREFIX + "counter").increment(3.2); // 自增 3.2(对应 Redis incrbyfloat 命令)
        
        // 获取自增后的计数器值
        String counter = template.opsForValue().get(KEY_PREFIX + "counter");
        System.out.println("counter = " + counter);
        
        // 4. 删除数据(根据 Key 删除)
        template.delete(KEY_PREFIX + "user:username:10");
    }
}

核心 API 说明

操作 API 方法 Redis 对应命令
存储字符串 opsForValue().set(key, value) SET
获取字符串 opsForValue().get(key) GET
整数自增 1 boundValueOps(key).increment() INCR
整数自增指定值 boundValueOps(key).increment(long delta) INCRBY
浮点数自增指定值 boundValueOps(key).increment(double delta) INCRBYFLOAT
删除数据 delete(key) DEL

Hash 数据类型测试

Hash 适用于存储对象(如用户、商品信息),格式为 key -> field -> value,支持单独操作对象的某个字段。可以自定义 RedisTemplate 配置序列化方式(默认 JDK 序列化不友好,改用 JSON 序列化)。

步骤 1:配置 RedisTemplate(自定义序列化)

package com.springboot.config;

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.RedisSerializer;

@Configuration
public class RedisConfig {
    // Redis Key 统一前缀
    public static final String KEY_PREFIX = "com:springboot:";

    /**
     * 自定义 RedisTemplate,配置 JSON 序列化(Key 用 String 序列化,Value 用 JSON 序列化)
     */
    @Bean
    public RedisTemplate<String, ?> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(redisConnectionFactory);
        
        // Key 序列化(String 序列化,保证 Key 可读性)
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        
        // Value 序列化(JSON 序列化,支持对象存储)
        template.setValueSerializer(RedisSerializer.json());
        template.setHashValueSerializer(RedisSerializer.json());
        
        return template;
    }
}

步骤 2:定义实体类(需实现 Serializable)

package com.springboot.entity;

import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;

// Lombok 注解:自动生成 getter/setter、toString 等方法
@Data
// 链式调用支持(如 new Emp().setId(10).setName("peppa"))
@Accessors(chain = true)
// 实现 Serializable 接口(支持序列化,用于 Redis 存储)
public class Emp implements Serializable {
    private Integer id;    // 员工 ID
    private String name;   // 员工姓名
    private String job;    // 员工职位
}

步骤 3:Hash 类型操作测试

package com.springboot;

import com.springboot.config.RedisConfig;
import com.springboot.entity.Emp;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Map;

@SpringBootTest
public class HashTest {

    // 注入 StringRedisTemplate(操作简单 Hash 数据)
    @Autowired
    private StringRedisTemplate template;

    // 注入自定义 RedisTemplate(操作对象类型 Hash 数据)
    @Autowired
    private RedisTemplate<String, Emp> redisTemplate;

    /**
     * 测试简单 Hash 操作(field 和 value 均为 String 类型)
     */
    @Test
    public void test() {
        // 单个字段存储(key: com:user:30,field: id,value: 30)对应 Redis HSET 命令
        template.opsForHash().put("com:user:30", "id", "30");
        
        // 批量字段存储(key: com:user:40,批量设置多个 field-value)对应 Redis HMSET 命令
        Map<String, ?> map = Map.of("id", "40", "username", "peppa", "phone", "123456");
        template.opsForHash().putAll("com:user:40", map);
    }

    /**
     * 测试对象类型 Hash 操作(存储对象、对象转 Hash 存储)
     */
    @Test
    public void object() {
        // 1. 直接存储对象(通过 JSON 序列化)
        Emp emp = new Emp().setId(10).setJob("dev").setName("peppa");
        redisTemplate.opsForValue().set("com:emp:10", emp);
        // 获取并打印对象
        System.out.println(redisTemplate.opsForValue().get("com:emp:10"));

        // 2. 对象转为 Map 存储(Hash 结构)
        Emp emp2 = new Emp().setId(20).setJob("dev").setName("peppa2");
        // 将对象字段转为 Map(field 为属性名,value 为属性值)
        Map<String, Object> empMap = Map.of(
            "id", emp2.getId(),
            "job", emp2.getJob(),
            "name", emp2.getName()
        );
        // 批量存储 Hash 数据
        redisTemplate.opsForHash().putAll("com:emp:20", empMap);
        // 获取 Hash 所有字段和值(对应 Redis HGETALL 命令)
        System.out.println(redisTemplate.opsForHash().entries("com:emp:20"));
    }
}

核心 API 说明

操作 API 方法 Redis 对应命令
单个字段存储 opsForHash().put(key, field, value) HSET
批量字段存储 opsForHash().putAll(key, map) HMSET
获取所有字段和值 opsForHash().entries(key) HGETALL
获取单个字段值 opsForHash().get(key, field) HGET
删除字段 opsForHash().delete(key, field) HDEL

List 数据类型测试

List 是有序列表(双向链表),支持从头部或尾部插入/删除数据,适用于实现队列、栈等场景。

测试代码

package com.springboot;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;

@SpringBootTest
public class ListTest {

    // 注入 StringRedisTemplate 操作 List 类型
    @Autowired
    private StringRedisTemplate template;

    @Test
    public void test() {
        // 1. 从列表头部插入数据(左进),对应 Redis LPUSH 命令
        template.opsForList().leftPush("com:user:list", "peppa");
        template.opsForList().leftPush("com:user:list", "lili");
        template.opsForList().leftPush("com:user:list", "lala");
        // 从列表尾部弹出数据(右出),对应 Redis RPOP 命令(队列模式:先进先出)
        System.out.println("右出数据:" + template.opsForList().rightPop("com:user:list"));

        // 2. 从列表尾部批量插入数据(右进),对应 Redis RPUSH 命令
        template.opsForList().rightPushAll("com:user:list", "peppa", "lili", "lala");
        // 从列表头部批量插入数据(左进)
        template.opsForList().leftPushAll("com:user:list", "peppa", "lili", "lala");
        // 从列表头部弹出数据(左出),对应 Redis LPOP 命令(栈模式:先进后出)
        System.out.println("左出数据:" + template.opsForList().leftPop("com:user:list"));

        // 3. 循环弹出列表中所有数据(右出)
        System.out.println("循环弹出所有数据:");
        while (template.opsForList().size("com:user:list") > 0) {
            System.out.println(template.opsForList().rightPop("com:user:list"));
        }
    }
}

核心 API 说明

操作 API 方法 Redis 对应命令 说明
头部插入单个数据 opsForList().leftPush(key, value) LPUSH 从列表左侧添加元素
头部插入多个数据 opsForList().leftPushAll(key, values) LPUSH 批量从左侧添加元素
尾部插入单个数据 opsForList().rightPush(key, value) RPUSH 从列表右侧添加元素
尾部插入多个数据 opsForList().rightPushAll(key, values) RPUSH 批量从右侧添加元素
头部弹出数据 opsForList().leftPop(key) LPOP 移除并返回左侧第一个元素
尾部弹出数据 opsForList().rightPop(key) RPOP 移除并返回右侧第一个元素
获取列表长度 opsForList().size(key) LLEN 返回列表元素个数

注意事项

  1. Key 命名规范:使用 业务:模块:标识 格式(如 com:user:10),避免 Key 冲突,提高可读性。
  2. 序列化方式:String 类型用 StringRedisTemplate(默认 String 序列化),对象类型用自定义 RedisTemplate(JSON 序列化),避免默认 JDK 序列化导致的乱码问题。
  3. 数据过期:可通过 template.expire(key, timeout, TimeUnit.SECONDS) 为 Key 设置过期时间,避免 Redis 内存溢出。
  4. 实体类要求:存储对象时,实体类需实现 Serializable 接口(JSON 序列化可不实现,但建议统一规范),且字段需提供 getter/setter 方法(Lombok @Data 注解可自动生成)。
posted @ 2026-01-14 14:05  Jing61  阅读(0)  评论(0)    收藏  举报