Я пытался реализовать кэширование, данные кэшируются в памяти, но не извлекаются из кеш -памяти, когда называют второй или третий раз, вместо этого они выбирают из БД каждый раз, когда вызывается. Вопрос в том, что почему он не получает кэшированные данные?
Какую ошибку я делаю? idk, если это возникает проблема < /p>
public ResponseEntity getActiveJobPostsByEnterpriseId(
@PathVariable Long enterpriseId,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "50") int size) {
Optional user = userService.findById(enterpriseId);
if (user.isPresent()) {
List response = demandMvpJobDetailsService.getActiveJobDetailsWithStats(enterpriseId, page, size);
return new ResponseEntity(response, HttpStatus.OK);
} else {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
}
@Override
@Transactional(readOnly = true)
@Cacheable(value = "activeJobsWithStats", key = "#enterpriseId + '_' + #page + '_' + #size", cacheManager = "customCacheManager")
public List getActiveJobDetailsWithStats(Long enterpriseId, int page, int size) {
Pageable pageable = PageRequest.of(page, size);
Page activeJobPosts = getActiveJobPostsByEnterpriseId(enterpriseId, pageable);
List content = activeJobPosts.getContent();
log.info("NotFetching from cache");
// Use transaction to fetch all necessary data
List response = new ArrayList();
for (EnterpriseJobDetailsModel job : content) {
JobDTO jobDTO = JobDTO.fromEntity(job);
Long applicationsCount = appliedJobByCandidiateRepository.countByEnterpriseJobDetailsModel(job);
Long viewsCount = jobViewsRepository.countByEnterpriseJobDetailsModel(job);
response.add(JobWithStatsDTO.from(jobDTO, applicationsCount, viewsCount));
}
log.info(response.toString());
return response;
}
< /code>
package com.campus.demandmvp.config;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
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;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableCaching
public class CacheConfig {
// Cache names as constants
public static final String ALL_PROFILES_CACHE = "allEnterpriseProfiles";
public static final String ACTIVE_JOBS_WITH_STATS = "activeJobsWithStats";
// TTL durations
private static final Duration DEFAULT_TTL = Duration.ofMinutes(30);
private static final Duration ALL_PROFILES_TTL = Duration.ofMinutes(15);
private static final Duration JOBS_TTL = Duration.ofMinutes(10);
@Bean
public ObjectMapper cacheObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.activateDefaultTyping(
LaissezFaireSubTypeValidator.instance,
ObjectMapper.DefaultTyping.NON_FINAL,
JsonTypeInfo.As.PROPERTY
);
return mapper;
}
@Bean
public GenericJackson2JsonRedisSerializer redisSerializer() {
return new GenericJackson2JsonRedisSerializer(cacheObjectMapper());
}
@Primary
@Bean(name = "customCacheManager")
public RedisCacheManager customCacheManager(RedisConnectionFactory connectionFactory, GenericJackson2JsonRedisSerializer redisSerializer) {
// Default cache configuration
RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(DEFAULT_TTL)
.disableCachingNullValues()
.serializeKeysWith(
RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())
)
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)
);
// Custom cache configurations
Map cacheConfigs = new HashMap();
cacheConfigs.put(ALL_PROFILES_CACHE, defaultConfig.entryTtl(ALL_PROFILES_TTL));
cacheConfigs.put(ACTIVE_JOBS_WITH_STATS, defaultConfig.entryTtl(JOBS_TTL));
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(defaultConfig)
.withInitialCacheConfigurations(cacheConfigs)
.transactionAware()
.build();
}
}
< /code>
redis output: < /strong> < /p>
127.0.0.1:6379> получить "ActiveJobswithstats :: 17_0_50"
"цин"java.util.arraylist", °
Подробнее здесь: https://stackoverflow.com/questions/796 ... d-from-cac