项目集成篇:springboot集成redis,实现缓存

在Spring Boot中集成Redis并实现缓存功能可以通过使用`spring-boot-starter-data-redis`和`@Cacheable`等注解来简化配置。以下是一个简单的示例,展示了如何设置一个基于Spring Boot的应用程序来使用Redis作为缓存。

1. 添加依赖

首先,在你的`pom.xml`文件中添加必要的依赖:

```xml

<dependencies>

<!-- Spring Boot Starter Web -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<!-- Spring Boot Starter Data Redis -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

<!-- Spring Boot Starter Cache (Optional, but recommended) -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-cache</artifactId>

</dependency>

<!-- Lombok (Optional) for reducing boilerplate code -->

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<optional>true</optional>

</dependency>

<!-- Test dependencies -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

```

2. 配置Redis连接

编辑`application.properties`或`application.yml`文件以包含Redis的连接信息。这里我们假设你已经有了一个运行中的Redis实例。

`application.properties`

```properties

Redis server configuration

spring.redis.host=localhost

spring.redis.port=6379

```

或者使用`application.yml`

```yaml

spring:

redis:

host: localhost

port: 6379

```

3. 启用缓存

确保在应用程序主类上启用缓存支持:

```java

package com.example;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication

@EnableCaching // Enable caching in the application

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class, args);

}

}

```

4. 创建缓存服务

创建一个服务类,并使用`@Cacheable`、`@CachePut`和`@CacheEvict`注解来定义缓存行为。

```java

package com.example.service;

import com.example.model.User;

import lombok.extern.slf4j.Slf4j;

import org.springframework.cache.annotation.CacheEvict;

import org.springframework.cache.annotation.CachePut;

import org.springframework.cache.annotation.Cacheable;

import org.springframework.stereotype.Service;

@Service

@Slf4j

public class UserService {

// 模拟用户数据获取(实际项目中应该是从数据库或其他来源获取)

private final Map<Integer, User> users = new ConcurrentHashMap<>();

@Cacheable(value = "users", key = "#id")

public User getUserById(Integer id) {

log.info("Fetching user from database with ID: {}", id);

return users.getOrDefault(id, null);

}

@CachePut(value = "users", key = "#user.id")

public User saveOrUpdateUser(User user) {

log.info("Saving or updating user in cache and database: {}", user);

users.put(user.getId(), user);

return user;

}

@CacheEvict(value = "users", key = "#id")

public void deleteUserById(Integer id) {

log.info("Deleting user from cache and database with ID: {}", id);

users.remove(id);

}

}

```

5. 创建控制器

创建一个REST控制器来暴露服务层的方法:

```java

package com.example.controller;

import com.example.model.User;

import com.example.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController

@RequestMapping("/api/users")

public class UserController {

@Autowired

private UserService userService;

@GetMapping("/{id}")

public User getUser(@PathVariable Integer id) {

return userService.getUserById(id);

}

@PostMapping

public User createUser(@RequestBody User user) {

return userService.saveOrUpdateUser(user);

}

@PutMapping("/{id}")

public User updateUser(@PathVariable Integer id, @RequestBody User user) {

user.setId(id);

return userService.saveOrUpdateUser(user);

}

@DeleteMapping("/{id}")

public void deleteUser(@PathVariable Integer id) {

userService.deleteUserById(id);

}

}

```

6. 创建实体类(如果需要)

根据你的需求创建实体类,例如`User.java`:

```java

package com.example.model;

import lombok.AllArgsConstructor;

import lombok.Data;

import lombok.NoArgsConstructor;

@Data

@NoArgsConstructor

@AllArgsConstructor

public class User {

private Integer id;

private String name;

private String email;

}

```

注意事项

  • 确保你的Redis服务器正在运行并且可以从应用程序访问。

  • 如果你在本地开发,请确保Redis服务已正确安装并在默认端口6379上运行。

  • 根据实际情况调整包名、路径以及其他细节。

  • 使用`@Cacheable`时,如果方法返回null,则不会将结果存储到缓存中。如果你希望缓存null值,可以考虑自定义缓存解析器。

  • 对于生产环境,建议配置Redis连接池、密码认证以及持久化选项等。

以上代码示例展示了如何在Spring Boot应用中集成Redis并实现缓存功能。希望这能帮助你开始构建自己的项目。如果有任何问题或需要进一步的帮助,请随时提问!

相关推荐
Cyan_RA920 分钟前
SpringMVC @RequestMapping的使用演示和细节 详解
java·开发语言·后端·spring·mvc·ssm·springmvc
MarkHard1236 小时前
如何利用redis使用一个滑动窗口限流
数据库·redis·缓存
island13148 小时前
【Redis#10】渐进式遍历 | 数据库管理 | redis_cli | RES
数据库·redis·bootstrap
心想事成的幸运大王8 小时前
Redis的过期策略
数据库·redis·缓存
用户21411832636029 小时前
Qwen3-Coder 实战!历史人物短视频一键生成,多分镜人物不崩,魔搭直接玩
后端
追逐时光者9 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 54 期(2025年9.8-9.14)
后端·.net
追逐时光者9 小时前
C#/.NET/.NET Core编程技巧练习集,配套详细的文章教程讲解!
后端·.net
AD钙奶-lalala9 小时前
SpringBoot实现WebSocket服务端
spring boot·后端·websocket
moxiaoran57539 小时前
Flask学习笔记(一)
后端·python·flask
你的人类朋友10 小时前
🔒什么是HMAC
后端·安全·程序员