Skip to content

Commit

Permalink
user fetch concept modify
Browse files Browse the repository at this point in the history
  • Loading branch information
IN40068837 authored and IN40068837 committed Dec 24, 2024
1 parent eb2f985 commit d57b1ca
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/main/java/com/iemr/hwc/utils/JwtAuthenticationUtil.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.iemr.hwc.utils;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -26,6 +27,8 @@ public class JwtAuthenticationUtil {
private JwtUtil jwtUtil;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private UserLoginRepo userLoginRepo;
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

public JwtAuthenticationUtil(CookieUtil cookieUtil, JwtUtil jwtUtil) {
Expand Down Expand Up @@ -73,6 +76,10 @@ public boolean validateUserIdAndJwtToken(String jwtToken) throws IEMRException {

// Check if user data is present in Redis
Users user = getUserFromCache(userId);
if (user == null) {
// If not in Redis, fetch from DB and cache the result
user = fetchUserFromDB(userId);
}
if (user == null) {
throw new IEMRException("Invalid User ID.");
}
Expand All @@ -89,11 +96,31 @@ private Users getUserFromCache(String userId) {
Users user = (Users) redisTemplate.opsForValue().get(redisKey);

if (user == null) {
logger.warn("User not found in Redis.");
logger.warn("User not found in Redis. Will try to fetch from DB.");
} else {
logger.info("User fetched successfully from Redis.");
}

return user; // Returns null if not found
}

private Users fetchUserFromDB(String userId) {
// This method will only be called if the user is not found in Redis.
String redisKey = "user_" + userId; // Redis key format

// Fetch user from DB
Users user = userLoginRepo.getUserByUserID(Long.parseLong(userId));

if (user != null) {
// Cache the user in Redis for future requests (cache for 30 minutes)
redisTemplate.opsForValue().set(redisKey, user, 30, TimeUnit.MINUTES);

// Log that the user has been stored in Redis
logger.info("User stored in Redis with key: " + redisKey);
} else {
logger.warn("User not found for userId: " + userId);
}

return user;
}
}

0 comments on commit d57b1ca

Please sign in to comment.