【详解】Spring整合Redis

打印 上一主题 下一主题

主题 1802|帖子 1802|积分 5406

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

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

x
目次
Spring整合Redis
1. 环境准备
1.1 技能栈
1.2 工具
2. 添加依靠
3. 配置Redis
4. 创建Redis配置类
5. 使用RedisTemplate
6. 测试
7. 总结
1. 添加依靠
2. 配置Redis毗连
3. 创建Redis配置类
4. 创建服务类
5. 创建控制器
6. 启动应用
7. 测试API
1. 添加依靠
2. 配置Redis毗连
application.properties
application.yml
3. 创建Redis配置类
4. 使用RedisTemplate
5. 运行和测试


Spring整合Redis

在现代Web应用开发中,缓存技能是提高应用性能的关键因素之一。Redis作为一个高性能的键值存储体系,被广泛应用于各种场景中,如数据缓存、消息队列等。本文将介绍怎样在Spring框架中整合Redis,实现数据的高效读取和存储。
1. 环境准备

1.1 技能栈



  • Spring Boot:2.5.0
  • Redis:6.0.9
  • Java:11
1.2 工具



  • IDEA:2021.1
  • Maven:3.8.1
2. 添加依靠

首先,在​​pom.xml​​文件中添加Spring Data Redis和Jedis(Redis客户端)的依靠:
  1. <dependencies>
  2.     <!-- Spring Boot Starter Data Redis -->
  3.     <dependency>
  4.         <groupId>org.springframework.boot</groupId>
  5.         <artifactId>spring-boot-starter-data-redis</artifactId>
  6.     </dependency>
  7.     <!-- Jedis Client -->
  8.     <dependency>
  9.         <groupId>redis.clients</groupId>
  10.         <artifactId>jedis</artifactId>
  11.     </dependency>
  12. </dependencies>
复制代码
3. 配置Redis

在​​application.properties​​或​​application.yml​​文件中配置Redis毗连信息:
  1. spring:
  2.   redis:
  3.     host: 127.0.0.1
  4.     port: 6379
  5.     password:
  6.     database: 0
  7.     jedis:
  8.       pool:
  9.         max-active: 8
  10.         max-wait: -1ms
  11.         max-idle: 8
  12.         min-idle: 0
复制代码
4. 创建Redis配置类

创建一个配置类来配置RedisTemplate,以便在项目中使用自定义的序列化方式:
  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.data.redis.connection.RedisConnectionFactory;
  4. import org.springframework.data.redis.core.RedisTemplate;
  5. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
  6. import org.springframework.data.redis.serializer.StringRedisSerializer;
  7. @Configuration
  8. public class RedisConfig {
  9.     @Bean
  10.     public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  11.         RedisTemplate<String, Object> template = new RedisTemplate<>();
  12.         template.setConnectionFactory(factory);
  13.         // 设置键的序列化方式
  14.         template.setKeySerializer(new StringRedisSerializer());
  15.         // 设置值的序列化方式
  16.         template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  17.         // 设置哈希键的序列化方式
  18.         template.setHashKeySerializer(new StringRedisSerializer());
  19.         // 设置哈希值的序列化方式
  20.         template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
  21.         template.afterPropertiesSet();
  22.         return template;
  23.     }
  24. }
复制代码
5. 使用RedisTemplate

在需要使用Redis的地方,通过​​@Autowired​​注入​​RedisTemplate​​,并使用其提供的方法进行操纵:
  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.data.redis.core.RedisTemplate;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. public class UserService {
  6.     @Autowired
  7.     private RedisTemplate<String, Object> redisTemplate;
  8.     public void setUser(String key, User user) {
  9.         redisTemplate.opsForValue().set(key, user);
  10.     }
  11.     public User getUser(String key) {
  12.         return (User) redisTemplate.opsForValue().get(key);
  13.     }
  14. }
复制代码
6. 测试

创建一个测试类来验证Redis的集成是否乐成:
  1. import org.junit.jupiter.api.Test;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.boot.test.context.SpringBootTest;
  4. @SpringBootTest
  5. public class UserServiceTest {
  6.     @Autowired
  7.     private UserService userService;
  8.     @Test
  9.     public void testSetAndGetUser() {
  10.         User user = new User("1", "张三");
  11.         userService.setUser("user:1", user);
  12.         User retrievedUser = userService.getUser("user:1");
  13.         System.out.println(retrievedUser);
  14.     }
  15. }
复制代码
7. 总结

通过上述步调,我们乐成地在Spring Boot项目中集成了Redis,并实现了基本的数据存储和读取功能。Redis的强大之处在于其高性能和丰富的数据结构支持,这使得它成为缓存和消息队列等场景的抱负选择。
希望本文对大家有所帮助,如果有任何题目或建议,接待留言交流!
以上就是关于Spring整合Redis的技能博客文章,希望能对你的学习和工作有所帮助。当然可以!Spring框架与Redis的整合在现代Web应用中非常常见,特别是在需要缓存数据以提高性能的环境下。下面是一个简单的示例,展示怎样在Spring Boot应用中集成Redis,并使用它来存储和检索数据。
1. 添加依靠

首先,在你的​​pom.xml​​文件中添加Spring Boot Starter Data Redis依靠:
  1. <dependencies>
  2.     <!-- Spring Boot Starter Data Redis -->
  3.     <dependency>
  4.         <groupId>org.springframework.boot</groupId>
  5.         <artifactId>spring-boot-starter-data-redis</artifactId>
  6.     </dependency>
  7.     <!-- Spring Boot Starter Web -->
  8.     <dependency>
  9.         <groupId>org.springframework.boot</groupId>
  10.         <artifactId>spring-boot-starter-web</artifactId>
  11.     </dependency>
  12.     <!-- Lombok for simplifying Java code -->
  13.     <dependency>
  14.         <groupId>org.projectlombok</groupId>
  15.         <artifactId>lombok</artifactId>
  16.         <optional>true</optional>
  17.     </dependency>
  18. </dependencies>
复制代码
2. 配置Redis毗连

在​​application.properties​​或​​application.yml​​文件中配置Redis毗连信息:
  1. # application.properties
  2. spring.redis.host=localhost
  3. spring.redis.port=6379
复制代码
或者使用YAML格式:
  1. # application.yml
  2. spring:
  3.   redis:
  4.     host: localhost
  5.     port: 6379
复制代码
3. 创建Redis配置类

创建一个配置类来配置RedisTemplate,这将用于与Redis进行交互:
  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.data.redis.connection.RedisConnectionFactory;
  4. import org.springframework.data.redis.core.RedisTemplate;
  5. import org.springframework.data.redis.serializer.StringRedisSerializer;
  6. @Configuration
  7. public class RedisConfig {
  8.     @Bean
  9.     public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  10.         RedisTemplate<String, Object> template = new RedisTemplate<>();
  11.         template.setConnectionFactory(factory);
  12.         template.setKeySerializer(new StringRedisSerializer());
  13.         template.setValueSerializer(new StringRedisSerializer());
  14.         return template;
  15.     }
  16. }
复制代码
4. 创建服务类

创建一个服务类来处理与Redis的交互逻辑:
  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.data.redis.core.RedisTemplate;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. public class CacheService {
  6.     @Autowired
  7.     private RedisTemplate<String, Object> redisTemplate;
  8.     public void setCacheData(String key, Object value) {
  9.         redisTemplate.opsForValue().set(key, value);
  10.     }
  11.     public Object getCacheData(String key) {
  12.         return redisTemplate.opsForValue().get(key);
  13.     }
  14.     public void deleteCacheData(String key) {
  15.         redisTemplate.delete(key);
  16.     }
  17. }
复制代码
5. 创建控制器

创建一个控制器来暴露REST API,以便客户端可以与缓存服务进行交互:
  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.web.bind.annotation.*;
  3. @RestController
  4. @RequestMapping("/cache")
  5. public class CacheController {
  6.     @Autowired
  7.     private CacheService cacheService;
  8.     @PostMapping("/set")
  9.     public String setCacheData(@RequestParam String key, @RequestParam String value) {
  10.         cacheService.setCacheData(key, value);
  11.         return "Data cached successfully";
  12.     }
  13.     @GetMapping("/get")
  14.     public Object getCacheData(@RequestParam String key) {
  15.         return cacheService.getCacheData(key);
  16.     }
  17.     @DeleteMapping("/delete")
  18.     public String deleteCacheData(@RequestParam String key) {
  19.         cacheService.deleteCacheData(key);
  20.         return "Data deleted from cache";
  21.     }
  22. }
复制代码
6. 启动应用

最后,创建一个主类来启动Spring Boot应用:
  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. @SpringBootApplication
  4. public class RedisDemoApplication {
  5.     public static void main(String[] args) {
  6.         SpringApplication.run(RedisDemoApplication.class, args);
  7.     }
  8. }
复制代码
7. 测试API

你可以使用Postman或其他HTTP客户端来测试这些API:


  • Set Cache Data: ​​POST /cache/set?key=myKey&value=myValue​​
  • Get Cache Data: ​​GET /cache/get?key=myKey​​
  • Delete Cache Data: ​​DELETE /cache/delete?key=myKey​​
这样,你就完成了一个简单的Spring Boot应用与Redis的整合示例。希望这个示例对你有帮助!如果有任何题目或需要进一步的解释,请随时告诉我。在Spring框架中整合Redis可以极大地提升应用的性能和相应速度,尤其是在处理高并发场景时。Redis作为一款高性能的键值对存储体系,常被用作缓存、消息队列等。Spring框架提供了​​spring-data-redis​​模块来简化与Redis的集成工作。
1. 添加依靠

首先,在你的项目中添加Spring Data Redis的依靠。如果你使用的是Maven,可以在​​pom.xml​​文件中添加如下依靠:
  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-data-redis</artifactId>
  4.     <version>2.7.0</version> <!-- 请根据实际情况调整版本 -->
  5. </dependency>
复制代码
如果使用Gradle,可以在​​build.gradle​​文件中添加:
  1. implementation 'org.springframework.boot:spring-boot-starter-data-redis:2.7.0' // 请根据实际情况调整版本
复制代码
2. 配置Redis毗连

在​​application.properties​​或​​application.yml​​中配置Redis的毗连信息:
application.properties

  1. spring.redis.host=localhost
  2. spring.redis.port=6379
  3. spring.redis.password=
  4. spring.redis.database=0
复制代码
application.yml

  1. spring:
  2.   redis:
  3.     host: localhost
  4.     port: 6379
  5.     password:
  6.     database: 0
复制代码
3. 创建Redis配置类

你可以创建一个配置类来配置​​RedisTemplate​​,这是Spring提供的用于操纵Redis的模板类。通过自定义​​RedisTemplate​​,你可以指定序列化方式等配置。
  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.data.redis.connection.RedisConnectionFactory;
  4. import org.springframework.data.redis.core.RedisTemplate;
  5. import org.springframework.data.redis.serializer.StringRedisSerializer;
  6. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  7. @Configuration
  8. public class RedisConfig {
  9.     @Bean
  10.     public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  11.         RedisTemplate<String, Object> template = new RedisTemplate<>();
  12.         template.setConnectionFactory(factory);
  13.         // 使用Jackson2JsonRedisSerializer来序列化和反序列化value对象
  14.         Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
  15.         
  16.         // 设置key和hashKey的序列化方式为StringRedisSerializer
  17.         template.setKeySerializer(new StringRedisSerializer());
  18.         template.setHashKeySerializer(new StringRedisSerializer());
  19.         
  20.         // 设置value和hashValue的序列化方式为Jackson2JsonRedisSerializer
  21.         template.setValueSerializer(jackson2JsonRedisSerializer);
  22.         template.setHashValueSerializer(jackson2JsonRedisSerializer);
  23.         
  24.         template.afterPropertiesSet();
  25.         return template;
  26.     }
  27. }
复制代码
4. 使用RedisTemplate

在需要使用Redis的地方,可以通过​​@Autowired​​注解注入​​RedisTemplate​​,然后使用它来进行各种操纵,如设置、获取、删除等。
  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.data.redis.core.RedisTemplate;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. public class UserService {
  6.     @Autowired
  7.     private RedisTemplate<String, Object> redisTemplate;
  8.     public void setUser(String key, User user) {
  9.         redisTemplate.opsForValue().set(key, user);
  10.     }
  11.     public User getUser(String key) {
  12.         return (User) redisTemplate.opsForValue().get(key);
  13.     }
  14.     public void deleteUser(String key) {
  15.         redisTemplate.delete(key);
  16.     }
  17. }
复制代码
5. 运行和测试

启动你的Spring Boot应用,并进行相应的测试,确保Redis能够正常工作。你可以在控制台中看到Redis的操纵日志,也可以使用Redis客户端工具(如Redis Desktop Manager)来查看Redis中的数据。
以上就是Spring整合Redis的基本步调和示例代码。希望这些信息对你有帮助!如果有任何题目或需要进一步的帮助,请随时告诉我。

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

使用道具 举报

0 个回复

倒序浏览

快速回复

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

本版积分规则

商道如狼道

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