项目集成篇: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并实现缓存功能。希望这能帮助你开始构建自己的项目。如果有任何问题或需要进一步的帮助,请随时提问!

相关推荐
YOU OU4 小时前
Redis基础常识与命令
数据库·redis·缓存
GetcharZp4 小时前
抛弃低效SSH!这套Ansible+Web可视化神器,让你天天准点下班!
后端
weixin_446260858 小时前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
吳所畏惧8 小时前
宝塔面板Redis密码修改指南:SSH命令修改 vs 面板UI界面修改,哪个更靠谱?
运维·服务器·数据库·redis·缓存·ssh
赵丙双9 小时前
Redis 概率相关的数据类型
redis
ttwuai9 小时前
Cursor 生成 CRUD 后,Go 后台接口别只测 200:JWT、RBAC 和 tenant_id 怎么验
开发语言·后端·golang
用户8356290780519 小时前
Python 实现 Excel 页面布局与打印设置自动化
后端·python
用户9931441579849 小时前
微服务框架中获取用户信息
后端
xuanWb9 小时前
手写一个 LLM API 网关:Anthropic 与 OpenAI 协议转换的完整实现
后端