Spring Boot 整合 Redis 步调详解

打印 上一主题 下一主题

主题 1009|帖子 1009|积分 3027

文章目录



  • 1. 引言
  • 2. 添加依靠
  • 3. 配置 Redis 连接信息
  • 4. 创建 Redis 操纵服务类
  • 5. 使用 RedisTemplate 或 ReactiveRedisTemplate
  • 6. 测试 Redis 功能
  • 7. 注意事项
  • 8. 总结
Redis 是一个高性能的键值存储系统,常用于缓存、消息队列等多种场景。将 Redis 与 Spring Boot 结合使用可以极大提升应用的性能和响应速率。本文将详细先容怎样在 Spring Boot 应用中整合 Redis,并通过示例代码展示具体实现步调。
1. 引言

随着互联网应用对快速读写数据的需求日益增长,传统的数据库已经难以满足某些特定场景下的性能要求。Redis 依附其内存级的数据访问速率、丰富的数据结构支持以及简朴易用的 API,成为了很多开发者的首选。接下来,我们将一步步先容怎样在 Spring Boot 中集成 Redis。
2. 添加依靠

首先,在 pom.xml 文件中添加 Spring Data Redis 和 Jedis(或 Lettuce)客户端的 Maven 依靠:
  1. <dependencies>
  2.         <dependency>
  3.              <groupId>org.springframework.boot</groupId>
  4.              <artifactId>spring-boot-starter-web</artifactId>
  5.          </dependency>
  6.        
  7.          <dependency>
  8.              <groupId>org.springframework.boot</groupId>
  9.              <artifactId>spring-boot-starter-test</artifactId>
  10.              <scope>test</scope>
  11.          </dependency>
  12.        
  13.          <!-- Spring Boot Starter for Redis -->
  14.          <dependency>
  15.              <groupId>org.springframework.boot</groupId>
  16.              <artifactId>spring-boot-starter-data-redis</artifactId>
  17.          </dependency>
  18.        
  19.          <dependency>
  20.              <groupId>org.projectlombok</groupId>
  21.              <artifactId>lombok</artifactId>
  22.          </dependency>
  23.        
  24.          <dependency>
  25.              <groupId>com.alibaba</groupId>
  26.              <artifactId>fastjson</artifactId>
  27.              <version>1.2.83</version>
  28.          </dependency>
  29.         
  30.     <!-- Jedis or Lettuce client -->
  31.     <!-- Choose one of the following two dependencies -->
  32.     <!-- For Jedis -->
  33.     <dependency>
  34.         <groupId>redis.clients</groupId>
  35.         <artifactId>jedis</artifactId>
  36.     </dependency>
  37.     <!-- Or for Lettuce -->
  38.     <dependency>
  39.         <groupId>io.lettuce</groupId>
  40.         <artifactId>lettuce-core</artifactId>
  41.     </dependency>
  42. </dependencies>
复制代码
3. 配置 Redis 连接信息

接下来,在 application.properties 或 application.yml 文件中配置 Redis 的连接参数。这里以 .yml 文件为例:
  1. server:
  2.   port: 8082
  3. spring:
  4.   data:
  5.     redis:
  6.       host: localhost
  7.       port: 6379
  8.       password: 123456
复制代码
4. 创建 Redis 操纵服务类

Java实体
  1. import lombok.AllArgsConstructor;
  2. import lombok.Data;
  3. import lombok.NoArgsConstructor;
  4. /**
  5. * @Description
  6. * @Author HaleyHu
  7. * @Date 2024/12/5 23:41
  8. */
  9. @Data
  10. @NoArgsConstructor
  11. @AllArgsConstructor
  12. public class User {
  13.     private Long id;
  14.     private String username;
  15.     private int age;
  16. }
复制代码
用户接口类
  1. import org.hbin.redis.entity.User;
  2. /**
  3. * @Description
  4. * @Author HaleyHu
  5. * @Date 2024/12/5 23:44
  6. */
  7. public interface UserService {
  8.     User query(Long id);
  9.     Boolean expired(Long id);
  10. }
复制代码
接口实现类
  1. import com.alibaba.fastjson.JSON;
  2. import lombok.RequiredArgsConstructor;
  3. import org.hbin.redis.entity.User;
  4. import org.hbin.redis.service.UserService;
  5. import org.springframework.data.redis.core.RedisTemplate;
  6. import org.springframework.stereotype.Service;
  7. /**
  8. * @Description
  9. * @Author HaleyHu
  10. * @Date 2024/12/5 23:46
  11. */
  12. @Service
  13. @RequiredArgsConstructor
  14. public class UserServiceImpl implements UserService {
  15.     private final RedisTemplate<String, String> redisTemplate;
  16.     private final String REDIS_PREFIX_KEY = "User::";
  17.     @Override
  18.     public User query(Long id) {
  19.         Object obj = redisTemplate.opsForValue().get("User::" + id);
  20.         if(obj != null) {
  21.             return JSON.parseObject(obj.toString(), User.class);
  22.         }
  23.         // 模拟从DB查询
  24.         User user = new User(id, "user" + id, 20);
  25.         redisTemplate.opsForValue().set(REDIS_PREFIX_KEY + id, JSON.toJSONString(user));
  26.         return user;
  27.     }
  28.     @Override
  29.     public Boolean expired(Long id) {
  30.         return redisTemplate.delete(REDIS_PREFIX_KEY + id);
  31.     }
  32. }
复制代码
Controller代码
  1. import lombok.RequiredArgsConstructor;
  2. import org.hbin.redis.entity.User;
  3. import org.hbin.redis.service.UserService;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RequestParam;
  6. import org.springframework.web.bind.annotation.RestController;
  7. /**
  8. * @Description
  9. * @Author HaleyHu
  10. * @Date 2024/12/5 23:46
  11. */
  12. @RequiredArgsConstructor
  13. @RestController
  14. public class UserController {
  15.     private final UserService userService;
  16.     @GetMapping("/query")
  17.     public User query(@RequestParam Long id) {
  18.         return userService.query(id);
  19.     }
  20.     @GetMapping("/expired")
  21.     public String expired(@RequestParam Long id) {
  22.         return userService.expired(id).toString();
  23.     }
  24. }
复制代码
如果你想处理更复杂的数据类型(如对象),则需要使用 RedisTemplate 并配置序列化器。例如,使用 Jackson JSON 序列化器:
  1. import com.fasterxml.jackson.databind.ObjectMapper;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.data.redis.connection.RedisConnectionFactory;
  5. import org.springframework.data.redis.core.RedisTemplate;
  6. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  7. import org.springframework.data.redis.serializer.StringRedisSerializer;
  8. @Configuration
  9. public class RedisConfig {
  10.     @Bean
  11.     public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  12.         RedisTemplate<String, Object> template = new RedisTemplate<>();
  13.         template.setConnectionFactory(factory);
  14.         Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
  15.         ObjectMapper objectMapper = new ObjectMapper();
  16.         serializer.setObjectMapper(objectMapper);
  17.         template.setValueSerializer(serializer);
  18.         template.setKeySerializer(new StringRedisSerializer());
  19.         template.setHashKeySerializer(new StringRedisSerializer());
  20.         template.setHashValueSerializer(serializer);
  21.         template.afterPropertiesSet();
  22.         return template;
  23.     }
  24. }
复制代码
5. 使用 RedisTemplate 或 ReactiveRedisTemplate

Spring Data Redis 提供了两种主要的方式来与 Redis 举行交互:同步方式 (RedisTemplate) 和响应式编程方式 (ReactiveRedisTemplate)。根据你的需求选择合适的方式。
同步方式 (RedisTemplate)
这是最常见的方式,适用于大多数应用场景。
响应式编程方式 (ReactiveRedisTemplate)
如果你的应用采取了响应式编程模型(如 WebFlux),那么 ReactiveRedisTemplate 可能更适合你。它允许你以非阻塞的方式与 Redis 举行通信。
6. 测试 Redis 功能

最后,我们可以通过编写单元测试来验证 Redis 的基本功能是否正常工作。也可以摆设运行上述步伐来验证。访问路径:
http://localhost:8082/query?id=1
http://localhost:8082/expired?id=1


7. 注意事项



  • 生产环境配置:在生产环境中摆设时,请确保精确配置 Redis 的安全设置(如暗码保护、网络限制等),并考虑启用长期化选项以防止数据丢失。
  • 性能优化:公道调解连接池参数,避免过多的连接斲丧资源;同时也可以根据业务特点选用合适的序列化器来进步性能。
  • 监控和维护:定期检查 Redis 的运行状态,及时清算过期数据,保持系统的稳定性和高效性。
8. 总结

通过上述步调,我们乐成地在 Spring Boot 应用中集成了 Redis,并实现了基本的数据缓存功能。这不但进步了应用的性能,还为开发者提供了更多灵活的数据管理本领。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

杀鸡焉用牛刀

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表