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 39e98b9 commit ccb4c30
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,7 @@ public interface IEMRUserRepositoryCustom extends CrudRepository<M_User, Long> {
@Query("UPDATE M_User u set u.StatusID = 2 where u.UserID = :userId")
int updateSetUserStatusActive(@Param("userId") Long userId);

@Query(" SELECT u FROM M_User u WHERE u.UserID = :UserID AND u.Deleted = false ")
public M_User getUserByUserID(@Param("UserID") Long UserID);

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.iemr.helpline104.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 IEMRUserRepositoryCustom iEMRUserRepositoryCustom;
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
M_User 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 M_User getUserFromCache(String userId) {
M_User user = (M_User) 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 M_User 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
M_User user = iEMRUserRepositoryCustom.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 ccb4c30

Please sign in to comment.