Skip to content

Commit e66e99d

Browse files
committed
Cache user data in Redis for faster retrieval
1 parent 9d27243 commit e66e99d

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

src/main/java/com/programming/userService/controller/UserController.java

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,9 +172,22 @@ public ResponseEntity listUserbyUsername(@RequestBody AuthUser user) {
172172
@GetMapping("/listUserbyId/{id}")
173173
public ResponseEntity listUserbyId(@PathVariable("id") String id) {
174174
try {
175-
AuthUser user = userRepository.findById(id).orElseThrow(() -> new Exception("User not found"));
176-
// Save user in Redis cache
175+
// Attempt to fetch user from Redis cache
176+
AuthUser cachedUser = (AuthUser) redisTemplate.opsForHash().get(USER_CACHE, id);
177+
178+
if (cachedUser != null) {
179+
// If user is found in Redis, return it
180+
return ResponseEntity.ok(cachedUser);
181+
}
182+
183+
// If user is not found in Redis, fetch from MongoDB
184+
AuthUser user = userRepository.findById(id)
185+
.orElseThrow(() -> new Exception("User not found"));
186+
187+
// Cache the user in Redis
177188
redisTemplate.opsForHash().put(USER_CACHE, id, user);
189+
190+
// Return the user data
178191
return ResponseEntity.ok(user);
179192
} catch (Exception e) {
180193
return ResponseEntity.internalServerError().body(e.getMessage());

0 commit comments

Comments
 (0)