Skip to content

Commit

Permalink
Merge pull request #147 from LionnoiL/118-add-cahing-to-user-findbyid
Browse files Browse the repository at this point in the history
adding caching to user methods
  • Loading branch information
KovalBohdan-0 authored Jun 9, 2024
2 parents 9936d75 + 53bd8bd commit e9a7f88
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ public void deleteUser(@ParameterId @PathVariable @Positive Long userId) {
User user = userService.findById(userId);
userService.checkAccess(user);
userService.deleteById(userId);
userService.evictCaches(userId, user);
log.info("User with id {} deleted.", userId);
}

Expand Down
14 changes: 14 additions & 0 deletions src/main/java/org/petmarket/users/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@
import org.petmarket.users.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
Expand Down Expand Up @@ -68,6 +70,7 @@ public static Long getCurrentUserId() {
return principal.getId();
}

@Cacheable(value = "users", key = "#username")
public User findByUsername(String username) throws ItemNotFoundException {
User user = userRepository.findByEmail(username)
.orElseThrow(() -> new ItemNotFoundException("User email not found"));
Expand Down Expand Up @@ -155,6 +158,10 @@ public UserContactsResponseDto getContacts(User user) {
return contacts;
}

@Caching(evict = {
@CacheEvict(value = "users", key = "#user.id"),
@CacheEvict(value = "users", key = "#user.email")
})
@Transactional
public User updateUser(User user, UserUpdateRequestDto request) {
String oldUserEmail = user.getEmail();
Expand All @@ -178,6 +185,13 @@ public void deleteById(Long userId) {
userRepository.setUserStatusToDeleted(userId);
}

@Caching(evict = {
@CacheEvict(value = "users", key = "#userId"),
@CacheEvict(value = "users", key = "#user.email")
})
public void evictCaches(Long userId, User user) {
}

private Set<UserPhone> mergePhones(User user, UserUpdateRequestDto request) {
Set<String> newPhones = request.getPhones();
String mainPhone = request.getMainPhone();
Expand Down

0 comments on commit e9a7f88

Please sign in to comment.