温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

从零搭建Spring Boot脚手架中如何整合Redis作为缓存

发布时间:2021-12-10 16:42:51 来源:亿速云 阅读:177 作者:柒染 栏目:大数据

从零搭建Spring Boot脚手架中如何整合Redis作为缓存

1. 引言

在现代Web应用开发中,缓存是提升系统性能的重要手段之一。Spring Boot快速开发框架,提供了对多种缓存技术的支持,其中Redis作为一种高性能的键值存储系统,被广泛应用于缓存场景。本文将详细介绍如何从零搭建一个Spring Boot脚手架,并整合Redis作为缓存。

2. 环境准备

在开始之前,我们需要准备以下环境:

  • JDK 1.8或更高版本
  • Maven 3.x或更高版本
  • IntelliJ IDEA或Eclipse IDE
  • Redis服务器

2.1 安装JDK

确保系统中已经安装了JDK,并且配置了环境变量。可以通过以下命令检查JDK版本:

java -version 

2.2 安装Maven

Maven是Java项目的构建工具,可以通过以下命令检查Maven版本:

mvn -v 

2.3 安装Redis

Redis可以通过以下命令在Linux系统中安装:

sudo apt-get install redis-server 

在Windows系统中,可以从Redis官网下载并安装。

3. 创建Spring Boot项目

3.1 使用Spring Initializr创建项目

打开Spring Initializr,选择以下配置:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.5.4
  • Group: com.example
  • Artifact: spring-boot-redis-demo
  • Name: spring-boot-redis-demo
  • Package Name: com.example.springbootredisdemo
  • Packaging: Jar
  • Java: 11

在Dependencies中添加以下依赖:

  • Spring Web
  • Spring Data Redis
  • Lombok

点击“Generate”按钮下载项目压缩包,解压后用IDE打开。

3.2 项目结构

项目结构如下:

spring-boot-redis-demo ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ └── example │ │ │ └── springbootredisdemo │ │ │ ├── SpringBootRedisDemoApplication.java │ │ │ ├── controller │ │ │ │ └── UserController.java │ │ │ ├── model │ │ │ │ └── User.java │ │ │ ├── repository │ │ │ │ └── UserRepository.java │ │ │ └── service │ │ │ ├── UserService.java │ │ │ └── impl │ │ │ └── UserServiceImpl.java │ │ └── resources │ │ ├── application.properties │ │ └── static │ │ └── templates │ └── test │ └── java │ └── com │ └── example │ └── springbootredisdemo │ └── SpringBootRedisDemoApplicationTests.java └── pom.xml 

4. 配置Redis

4.1 添加Redis依赖

pom.xml中,确保已经添加了Spring Data Redis依赖:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 

4.2 配置Redis连接

application.properties中,添加Redis连接配置:

# Redis配置 spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= spring.redis.timeout=2000 spring.redis.database=0 

4.3 配置RedisTemplate

在Spring Boot中,RedisTemplate是操作Redis的核心类。我们可以通过配置类来自定义RedisTemplate

创建一个配置类RedisConfig.java

package com.example.springbootredisdemo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } 

5. 实现缓存功能

5.1 创建实体类

创建一个简单的User实体类:

package com.example.springbootredisdemo.model; import lombok.Data; import java.io.Serializable; @Data public class User implements Serializable { private Long id; private String name; private String email; } 

5.2 创建Repository

创建一个UserRepository接口,用于模拟数据库操作:

package com.example.springbootredisdemo.repository; import com.example.springbootredisdemo.model.User; import org.springframework.stereotype.Repository; import java.util.HashMap; import java.util.Map; @Repository public class UserRepository { private final Map<Long, User> userMap = new HashMap<>(); public User findById(Long id) { return userMap.get(id); } public void save(User user) { userMap.put(user.getId(), user); } } 

5.3 创建Service

创建一个UserService接口及其实现类UserServiceImpl,并在其中实现缓存逻辑:

package com.example.springbootredisdemo.service; import com.example.springbootredisdemo.model.User; public interface UserService { User findById(Long id); void save(User user); } 
package com.example.springbootredisdemo.service.impl; import com.example.springbootredisdemo.model.User; import com.example.springbootredisdemo.repository.UserRepository; import com.example.springbootredisdemo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Override @Cacheable(value = "user", key = "#id") public User findById(Long id) { System.out.println("从数据库中获取用户信息"); return userRepository.findById(id); } @Override public void save(User user) { userRepository.save(user); } } 

5.4 创建Controller

创建一个UserController类,用于处理HTTP请求:

package com.example.springbootredisdemo.controller; import com.example.springbootredisdemo.model.User; import com.example.springbootredisdemo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public User getUser(@PathVariable Long id) { return userService.findById(id); } @PostMapping public void saveUser(@RequestBody User user) { userService.save(user); } } 

6. 测试缓存功能

6.1 启动Redis服务器

确保Redis服务器已经启动,可以通过以下命令检查Redis状态:

redis-cli ping 

如果返回PONG,则表示Redis服务器正常运行。

6.2 启动Spring Boot应用

在IDE中运行SpringBootRedisDemoApplication类,启动Spring Boot应用。

6.3 测试缓存

使用Postman或curl工具发送HTTP请求,测试缓存功能。

6.3.1 添加用户

发送POST请求添加用户:

curl -X POST -H "Content-Type: application/json" -d '{"id":1,"name":"John Doe","email":"john@example.com"}' http://localhost:8080/users 

6.3.2 获取用户

发送GET请求获取用户信息:

curl http://localhost:8080/users/1 

第一次请求时,控制台会输出“从数据库中获取用户信息”,表示数据是从数据库中获取的。再次请求时,控制台不会输出该信息,表示数据是从缓存中获取的。

7. 缓存配置优化

7.1 配置缓存过期时间

application.properties中,可以配置缓存的过期时间:

# 缓存配置 spring.cache.type=redis spring.cache.redis.time-to-live=60000 

7.2 配置缓存管理器

可以通过配置类自定义缓存管理器:

package com.example.springbootredisdemo.config; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import java.time.Duration; @Configuration @EnableCaching public class CacheConfig { @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofMinutes(10)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); return RedisCacheManager.builder(redisConnectionFactory) .cacheDefaults(cacheConfiguration) .build(); } } 

8. 总结

通过本文的介绍,我们学习了如何从零搭建一个Spring Boot脚手架,并整合Redis作为缓存。我们详细介绍了环境准备、项目创建、Redis配置、缓存功能的实现以及缓存配置的优化。希望本文能够帮助读者在实际项目中更好地应用Redis缓存技术,提升系统性能。

9. 参考资料


以上内容为《从零搭建Spring Boot脚手架中如何整合Redis作为缓存》的完整文章,共计约7500字。希望对你有所帮助!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI