我正在嘗試通過@Cacheable注釋將 jpa 物體快取到 redis 。
[RedisConfig.class]
@Configuration
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(host, port);
}
@Bean
public RedisTemplate<?, ?> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory());
return redisTemplate;
}
}
【服務層】
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class RoomQueryService {
private final RoomRepository roomRepository;
@Cacheable(value = "search", key = "#code")
public Room searchRoomByCode(String code) {
return roomRepository.findByCode(code).orElseThrow(RoomNotFoundException::new);
}
}
執行上面的代碼時,它會拋出以下錯誤。
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.redis.serializer.SerializationException: Cannot serialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [slido.slidoclone.room.domain.Room]] with root cause
可能是因為 DefaultSerializer 無法序列化 jpa 物體類。
所以我在RedisConfig中添加了以下2行。
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
但它拋出同樣的錯誤。
搜索之后,我找到了2個解決方案。
- 添加
implements Serializable到 JPA 物體 - 在
@Cacheable注解中使用 cacheManager
我很好奇在生產中使用哪種方法。
謝謝。
uj5u.com熱心網友回復:
我認為您RedisTemplate實際上并未在任何地方使用。您必須提供一個RedisCacheConfiguration(取自“Spring Boot Cache with Redis”):
@Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(60))
.disableCachingNullValues()
.serializeValuesWith(SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
}
uj5u.com熱心網友回復:
添加注解@EnableCaching,看看效果。
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
@EnableCaching
public class RoomQueryService {
private final RoomRepository roomRepository;
@Cacheable(value = "search", key = "#code")
public Room searchRoomByCode(String code) {
return
roomRepository.findByCode(code).orElseThrow(RoomNotFoundException::new);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/342769.html
上一篇:Spring:帶有Jpa和Kafka的ChainedKafkaTransactionManager不是原子的?
下一篇:如何從服務類回滾事務?
