Redis Caching -Problem in Java: Daten werden zwischengespeichert, aber nicht vom Cache abgerufen, wenn sie aufgerufen weJava

Java-Forum
Anonymous
 Redis Caching -Problem in Java: Daten werden zwischengespeichert, aber nicht vom Cache abgerufen, wenn sie aufgerufen we

Post by Anonymous »

Ich habe versucht, das Caching zu implementieren, Daten werden im Speicher zwischengespeichert, aber nicht aus dem Cache -Speicher abgeholt, wenn es das zweite oder dritte Mal aufgerufen wird, stattdessen holt es sich jedes Mal von DB ab, wenn es aufgerufen wird. Die Frage ist Warum holt es keine zwischengespeicherten Daten?
Welchen Fehler mache ich? IDK, wenn dies das Problem basiert < /p>
@GetMapping("/listOfActiveJobsByEnterprise/enterpriseId/{enterpriseId}")
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>
```java
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:


127.0.0.1:6379> get "activeJobsWithStats::17_0_50"
"["java.util.ArrayList",[{"@class":"com.campus.demandmvp.response.JobWithStatsDTO","job":{"@class":"com.campus.demandmvp.response.JobDTO","id":67,"jobpost":"\n , Python assessment , The ideal candidate will have a strong work ethic and attention to detail.","user":{"@class":"com.campus.demandmvp.response.UserDTO","id":17,"email":"k@gmail.com","firstName":"Kotresh","lastName":"Patil","nameOfEnterPrise":"Kotresh Patil","pnCode":"+91","phoneNumber":70220,"creationDate":1745633466159,"profilePhoto":"enterprise_profile_75a79967-29ab-4b21-8d50-73b935423cf2.jpeg","accessWhatsapp":false,"userType":"PROFESSOR","emailVerified":false},"jobPostDate":1745646948750,"status":true,"uniqueLink":"","areaOfEvaluation":"\"Algorithm design\",\"Solving real-world problems\",\"Consistency in naming\",\"Repository management\",\"Writing docstrings\",\"Breaking down tasks\",\"Planning workflows\"","other_benifts":"NOT_APPLICABLE","jobTitle":"Python Work Ethic","job_comments":" , Python assessment , The ideal candidate will have a strong work ethic and attention to detail.","companyOverview":"","krrs":"NOT_APPLICABLE","keyQualifications":"NOT_APPLICABLE","presence":"NOT_APPLICABLE","type_of_job":"TIER_3","skill_tags":"Python programming proficiency,Debugging and problem-solving,Code quality and best practices,Understanding of algorithms,Hands-on coding exercises,Attention to detail in code,Version control and git usage,Code documentation practices,Task management and focus,Time management under deadlines","jobCountry":"NOT_APPLICABLE","jobCity":"NOT_APPLICABLE","suggestedCompensationMin":"0","suggestedCompensationMax":"0","noOfInterviews":100,"salaryCurrency":"NOT_APPLICABLE","minSalary":0.0,"maxSalary":0.0,"compensationFrequency":"NOT_APPLICABLE","minExperience":0,"maxExperience":1,"education_level":null,"jobtype":"NOT_APPLICABLE"},"totalCandidatesAppliedForTheParticularJob":0,"jobViewCount":0},{"@class":"com.campus.demandmvp.response.JobWithStatsDTO","job":{"@class":"com.campus.demandmvp.response.JobDTO","id":66,"jobpost":"\n , Java developer , The ideal candidate will have a strong work ethic and attention to detail.","user":{"@class":"com.campus.demandmvp.response.UserDTO","id":17,"email":"k@gmail.com","firstName":"Kotresh","lastName":"Patil","nameOfEnterPrise":"Kotresh Patil","pnCode":"+91","phoneNumber":7800,"creationDate":1745633466159,"profilePhoto":"enterprise_profile_75a79967-29ab-4b21-8d50-73b935423cf2.jpeg","accessWhatsapp":false,"userType":"PROFESSOR","emailVerified":false},"jobPostDate":1745643926017,"status":true,"uniqueLink":\","areaOfEvaluation":"\"Branching and merging\",\"Logic formulation\",\"Unit testing\",\"Code accuracy\",\"Code reviews\",\"Time management\",\"Maven/Gradle usage\"","other_benifts":"NOT_APPLICABLE","jobTitle":"Java Developer Assessment","job_comments":" , Java developer , The ideal candidate will have a strong work ethic and attention to detail.","companyOverview":"","krrs":"NOT_APPLICABLE","keyQualifications":"NOT_APPLICABLE","presence":"NOT_APPLICABLE","type_of_job":"TIER_3","skill_tags":"Java Programming Proficiency,Object-Oriented Design Principles,Algorithm and Data Structures,Version Control Systems (Git),Problem Solving Skills,Software Debugging and Testing,Attention to Detail,Team Collaboration Skills,Work Ethic Evaluation,Understanding of Build Tools","jobCountry":"NOT_APPLICABLE","jobCity":"NOT_APPLICABLE","suggestedCompensationMin":"0","suggestedCompensationMax":"0","noOfInterviews":100,"salaryCurrency":"NOT_APPLICABLE","minSalary":0.0,"maxSalary":0.0,"compensationFrequency":"NOT_APPLICABLE","minExperience":0,"maxExperience":1,"education_level":null,"jobtype":"NOT_APPLICABLE"},"totalCandidatesAppliedForTheParticularJob":0,"jobViewCount":1},{"@class":"com.campus.demandmvp.response.JobWithStatsDTO","job":

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post