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

相关推荐
大志说编程1 分钟前
LangChain框架入门16:智能客服系统RAG应用实战
后端·langchain·aigc
沸腾_罗强16 分钟前
Redis内存爆了
后端
天天摸鱼的java工程师22 分钟前
Snowflake 雪花算法优缺点(Java老司机实战总结)
java·后端·面试
海梨花1 小时前
【从零开始学习Redis】项目实战-黑马点评D2
java·数据库·redis·后端·缓存
bug菌1 小时前
零基础也能做出AI应用?Trae是如何打破编程"高墙"的?
后端·ai编程·trae
Java技术小馆1 小时前
重构 Controller 的 7 个黄金法则
java·后端·面试
用户4099322502121 小时前
容器化部署FastAPI应用:如何让你的任务系统代码在云端跳舞?
后端·ai编程·trae
Java水解1 小时前
MySQL 亿级数据表平滑分表实践:基于时间分片的架构演进
后端·mysql
Neo2551 小时前
Spring 5.3.x 源码:invokeBeanFactoryPostProcessors()详解
后端