(七)Spring Boot学习——Redis使用

有部分内容是常用的,为了避免每次都查询数据库,将部分数据存入Redis。

一、 下载并安装 Redis

Windows 版的 Redis 官方已不再维护,你可以使用 微软提供的 Redis for Windows 版本 或者 使用 WSL(Windows Subsystem for Linux)安装 Redis

  1. 下载 Redis for Windows

  2. 解压并进入 Redis 目录

    cd C:\Redis

  3. 启动 Redis 服务器

    redis-server.exe redis.windows.conf

  4. 验证 Redis 是否启动 打开另一个 命令行窗口(CMD),输入:

    redis-cli.exe ping

    如果返回:

    PONG

    说明 Redis 服务器已成功启动 🎉。

二、 配置 Redis

1. 添加 Redis 依赖

如果使用 Maven ,在 pom.xml 添加:

XML 复制代码
<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-data-redis</artifactId> 
</dependency>

⚠️ Spring Boot 2.0+ 默认使用 Lettuce,而不是 Jedis。如果要使用 Jedis,需要额外添加依赖

XML 复制代码
<dependency> 
    <groupId>redis.clients</groupId> 
    <artifactId>jedis</artifactId> 
</dependency>

✅ 2. 配置 Redis 连接

application.ymlapplication.properties 配置 Redis 连接信息。

🔹 application.properties 配置

XML 复制代码
#配置redis
spring.data.redis.host=127.0.0.1
spring.data.redis.port=6379
spring.data.redis.password=
spring.data.redis.database=0
spring.data.redis.timeout=5000ms
spring.data.redis.lettuce.pool.max-active=8
spring.data.redis.lettuce.pool.max-idle=8
spring.data.redis.lettuce.pool.min-idle=0
spring.data.redis.lettuce.pool.max-wait=-1ms

⚠️ 注意:

  • host:Redis 服务器地址
  • port:Redis 端口(默认 6379)
  • password:如果 Redis 没有密码,保持为空
  • database:选择 Redis 数据库(默认 0)
  • timeout:连接超时时间(5 秒)

✅ 3. 编写 Redis 工具类

可以使用 RedisTemplate 来操作 Redis。

🔹 RedisConfig.java

创建一个 Redis 配置类,注入 RedisTemplate

java 复制代码
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 使用 String 序列化 key,避免乱码
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}

✅ 4. 在 Service 中使用 Redis

你可以直接在 RedisService 中使用 RedisTemplate 提供的方法来存取数据。

🔹 (1) 操作字符串

Redis 的 opsForValue() 主要用于存取字符串数据:

java 复制代码
@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 存储字符串数据
    public void setString(String key, String value, long timeout) {
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    // 获取字符串数据
    public String getString(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }

    // 删除 Key
    public void deleteKey(String key) {
        redisTemplate.delete(key);
    }
}

✅ 2. 操作哈希表(Hash)

Redis 的 opsForHash() 适用于存储对象、键值对等。

java 复制代码
@Service
public class RedisHashService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 设置 Hash 值
    public void setHash(String key, String field, String value) {
        redisTemplate.opsForHash().put(key, field, value);
    }

    // 获取 Hash 值
    public Object getHash(String key, String field) {
        return redisTemplate.opsForHash().get(key, field);
    }

    // 获取整个 Hash 对象
    public Map<Object, Object> getAllHash(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    // 删除 Hash 字段
    public void deleteHashField(String key, String field) {
        redisTemplate.opsForHash().delete(key, field);
    }
}

示例

redisHashService.setHash("user:1001", "name", "Tom"); String name = redisHashService.getHash("user:1001", "name"); // "Tom"


✅ 3. 操作列表(List)

Redis opsForList() 适用于存储列表数据(如消息队列、排行榜等)。

java 复制代码
@Service
public class RedisListService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 左侧推入列表
    public void leftPush(String key, String value) {
        redisTemplate.opsForList().leftPush(key, value);
    }

    // 右侧推入列表
    public void rightPush(String key, String value) {
        redisTemplate.opsForList().rightPush(key, value);
    }

    // 获取列表范围
    public List<Object> getListRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    // 弹出左侧元素
    public Object leftPop(String key) {
        return redisTemplate.opsForList().leftPop(key);
    }
}

示例

redisListService.leftPush("queue", "task1");

redisListService.leftPush("queue", "task2");

List<Object> tasks = redisListService.getListRange("queue", 0, -1); // ["task2", "task1"]


✅ 4. 操作集合(Set)

Redis opsForSet() 适用于存储无序唯一集合(如标签、好友列表等)。

java 复制代码
@Service
public class RedisSetService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 添加集合元素
    public void addToSet(String key, String value) {
        redisTemplate.opsForSet().add(key, value);
    }

    // 获取集合中的所有元素
    public Set<Object> getSetMembers(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    // 删除集合中的某个元素
    public void removeFromSet(String key, String value) {
        redisTemplate.opsForSet().remove(key, value);
    }
}

示例

redisSetService.addToSet("users", "Alice");

redisSetService.addToSet("users", "Bob");

Set<Object> users = redisSetService.getSetMembers("users"); // ["Alice", "Bob"]


✅ 5. 在 Controller 中调用

你可以在 Controller 里调用 RedisService 来测试 Redis 的使用:

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisService redisService;

    // 存储 Key-Value
    @PostMapping("/set")
    public String setKey(@RequestParam String key, @RequestParam String value) {
        redisService.setString(key, value, 3600);
        return "存储成功";
    }

    // 获取 Key 的值
    @GetMapping("/get")
    public String getKey(@RequestParam String key) {
        return redisService.getString(key);
    }

    // 删除 Key
    @DeleteMapping("/delete")
    public String deleteKey(@RequestParam String key) {
        redisService.deleteKey(key);
        return "删除成功";
    }
}
相关推荐
阿阳微客1 小时前
Steam 搬砖项目深度拆解:从抵触到真香的转型之路
前端·笔记·学习·游戏
XMYX-03 小时前
Spring Boot + Prometheus 实现应用监控(基于 Actuator 和 Micrometer)
spring boot·后端·prometheus
@yanyu6664 小时前
springboot实现查询学生
java·spring boot·后端
酷爱码5 小时前
Spring Boot项目中JSON解析库的深度解析与应用实践
spring boot·后端·json
陈阿土i5 小时前
SpringAI 1.0.0 正式版——利用Redis存储会话(ChatMemory)
java·redis·ai·springai
bing_1586 小时前
跨多个微服务使用 Redis 共享数据时,如何管理数据一致性?
redis·微服务·mybatis
java干货6 小时前
虚拟线程与消息队列:Spring Boot 3.5 中异步架构的演进与选择
spring boot·后端·架构
Chef_Chen6 小时前
从0开始学习R语言--Day18--分类变量关联性检验
学习
键盘敲没电6 小时前
【IOS】GCD学习
学习·ios·objective-c·xcode