SpringDataRedis使用一般流程
目录结构:
- 初始设置
- 方式一:自定义序列化(key→String序列化 value→Json序列化)
- 方式二:(key,value都String序列化) (推荐)
- Spring Cache 简化项目中的复杂逻辑 (后包含详细使用方法)
-
初始设置
<!--依赖引入--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
spring: redis: host: 172.22.128.100 port: 6379 password: 123321 timeout: 2000ms # 客户端连接超时时间(2秒) database: 0 lettuce: pool: max-active: 8 max-wait: 100ms # 连接池等待时间 max-idle: 8 min-idle: 0
//简单使用 @Autowired private RedisTemplate redisTemplate; @Test void testString() { redisTemplate.opsForValue().set("name", "Niko"); Object name = redisTemplate.opsForValue().get("name"); System.out.println("name = " + name); }
上面存储的序列化默认使用
JdkSerializationRedisSerializer
。此序列化器会把键对象序列化为字节数组,序列化后的数据可读性较差;如上是默认序列化的存储内容👆
占用大量空间,可读性差,我们采用两种方式来优化。
-
方式一:自定义序列化(key→String序列化 value→Json序列化)
// 添加配置类 @Configuration // 声明这是一个Spring配置类 public class RedisConfig { @Bean // 将方法返回的对象注册为Spring容器中的Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory){ // 创建RedisTemplate对象,指定Key为String类型,Value为Object类型 RedisTemplate<String, Object> template = new RedisTemplate<>(); // 设置Redis连接工厂(自动注入) template.setConnectionFactory(connectionFactory); // 创建JSON序列化工具,使用Jackson库将对象序列化为JSON格式 GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer(); // 设置Key的序列化方式为String序列化 template.setKeySerializer(RedisSerializer.string()); template.setHashKeySerializer(RedisSerializer.string()); // 设置Value的序列化方式为JSON序列化 template.setValueSerializer(jsonRedisSerializer); template.setHashValueSerializer(jsonRedisSerializer); return template; } } // 注入 @Autowired private RedisTemplate<String,Object> redisTemplate; // 使用 @Test void testObject() { User user = new User("Niko", 20); redisTemplate.opsForValue().set("user1", user); User user1 = (User) redisTemplate.opsForValue().get("user"); System.out.println("user1 = " + user1); }
String序列化就是直接存原始字符串,Json序列化可以把对象自动转成json字符串存储,接收数据时再自动转回对象。
这时,[String,String]的数据再redis中的存储就是正常的原始字符串,[String,Object]的存储如下
你会发现这里为了反序列化的时候找到原始类型,最上方多存了一行类位置的信息,这可能造成空间浪费,这也是这种方法的缺点,因此实际推荐第二种方式
-
方式二:(key,value都String序列化) (推荐)
恰好
StringRedisTemplate
默认都是这样序列化的 直接使用就可以这是恰好StringRedisTemplate
默认都是这样序列化的 直接使用就可以,不需要自己加配置类了。因为都是默认存储字符串,对象的存储需要我们手动将其转为Json类型字符串,取用时再将字符串转为对象,这个过程可以使用Json转换的工具,这里我是用SpringMVC自带的
@Autowired private StringRedisTemplate stringRedisTemplate; // SpringMVC 提供的工具类,用于将对象序列化为JSON格式 private static final ObjectMapper mapper = new ObjectMapper(); @Test void testObjectJson() throws JsonProcessingException { User user = new User("Donk", 17); // 手动序列化为json然后直接存储json字符串 String json = mapper.writeValueAsString(user); stringRedisTemplate.opsForValue().set("user2", json); // 手动处理返回的json字符串 String jsonUser = stringRedisTemplate.opsForValue().get("user2"); User user2 = mapper.readValue(jsonUser, User.class); System.out.println("user2 = " + user2); }
我们可以看到这样存储的就是原始的Json字符串了
-
Spring Cache 简化项目中的逻辑
项目中常用缓存相关的代码逻辑,可以使用Spring Cache简化:
如:”检测缓存中是否有这个值,没找到就先在数据库中查询使用,并将查询结果存入缓存中”这样常见的缓存相关逻辑,可以使用一个注释**
@Cacheable
** 替代-
具体使用
Spring Cache 是 Spring 框架提供的一个抽象缓存层,它允许你通过注解的方式将缓存功能集成到 Spring 应用程序中,从而简化缓存操作的逻辑。以下是使用 Spring Cache 简化项目逻辑的详细方式:
1. 引入依赖
首先,你需要在项目中引入 Spring Cache 相关的依赖。如果你使用的是 Maven 项目,可以在
pom.xml
中添加以下依赖:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
2. 启用缓存功能
在 Spring Boot 应用的主类上添加
@EnableCaching
注解来启用缓存功能:import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } }
3. 配置缓存管理器
Spring Cache 支持多种缓存实现,如 Redis、Ehcache 等。你需要配置相应的缓存管理器。以下是使用 Redis 作为缓存的配置示例:
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 org.springframework.data.redis.serializer.StringRedisSerializer; import java.time.Duration; @Configuration @EnableCaching public class CacheConfig { @Bean public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofMinutes(10)) // 设置缓存过期时间为 10 分钟 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); return RedisCacheManager.builder(redisConnectionFactory) .cacheDefaults(cacheConfig) .build(); } }
4. 使用缓存注解简化逻辑
Spring Cache 提供了多个注解,用于实现不同的缓存操作。以下是几个常用注解的使用示例:
@Cacheable
用于标记一个方法的返回值可以被缓存。当调用该方法时,Spring Cache 会先检查缓存中是否存在与该方法参数对应的缓存数据,如果存在则直接返回缓存中的数据,否则执行方法体中的逻辑,并将返回结果存入缓存。
import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class UserService { @Cacheable(value = "users", key = "#id") public User getUserById(Long id) { // 模拟从数据库中获取用户信息 return userRepository.findById(id); } }
在上述代码中,
@Cacheable
注解的value
属性指定了缓存的名称为users
,key
属性指定了缓存的键,这里使用方法的参数id
作为键。@CachePut
用于更新缓存。无论缓存中是否存在对应的数据,都会执行方法体中的逻辑,并将返回结果存入缓存。
import org.springframework.cache.annotation.CachePut; import org.springframework.stereotype.Service; @Service public class UserService { @CachePut(value = "users", key = "#user.id") public User updateUser(User user) { // 模拟更新数据库中的用户信息 return userRepository.save(user); } }
在上述代码中,
@CachePut
注解会在更新数据库中的用户信息后,将更新后的用户信息存入users
缓存中。@CacheEvict
用于清除缓存。可以指定清除特定的缓存数据或清除整个缓存。
import org.springframework.cache.annotation.CacheEvict; import org.springframework.stereotype.Service; @Service public class UserService { @CacheEvict(value = "users", key = "#id") public void deleteUser(Long id) { // 模拟从数据库中删除用户信息 userRepository.deleteById(id); } @CacheEvict(value = "users", allEntries = true) public void clearUserCache() { // 清除 users 缓存中的所有数据 } }
在上述代码中,
@CacheEvict
注解的key
属性指定了要清除的缓存键,allEntries
属性为true
表示清除整个缓存。5. 总结
通过使用 Spring Cache 的注解,你可以避免手动编写复杂的缓存操作代码,将缓存逻辑与业务逻辑分离,使代码更加简洁、易读和易于维护。同时,Spring Cache 支持多种缓存实现,你可以根据项目的需求选择合适的缓存管理器。
-