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

相关推荐
Kiri霧2 小时前
Rust开发环境搭建
开发语言·后端·rust
间彧3 小时前
Spring事件监听与消息队列(如Kafka)在实现解耦上有何异同?
后端
间彧3 小时前
Java如何自定义事件监听器,有什么应用场景
后端
叶梅树3 小时前
从零构建A股量化交易工具:基于Qlib的全栈系统指南
前端·后端·算法
间彧3 小时前
CopyOnWriteArrayList详解与SpringBoot项目实战
后端
间彧3 小时前
SpringBoot @FunctionalInterface注解与项目实战
后端
程序员小凯3 小时前
Spring Boot性能优化详解
spring boot·后端·性能优化
Achou.Wang3 小时前
源码分析 golang bigcache 高性能无 GC 开销的缓存设计实现
开发语言·缓存·golang
Asthenia04124 小时前
问题复盘:飞书OAuth登录跨域Cookie方案探索与实践
后端
tuine4 小时前
SpringBoot使用LocalDate接收参数解析问题
java·spring boot·后端