Skip to content

Commit

Permalink
Merge pull request #139 from LionnoiL/118-add-cahing-to-user-findbyid
Browse files Browse the repository at this point in the history
adding caching to findById for user
  • Loading branch information
KovalBohdan-0 authored May 26, 2024
2 parents 8af57d5 + df53beb commit 90f103d
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,12 @@
<version>6.1.7.Final</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>3.3.0</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
Expand Down
16 changes: 16 additions & 0 deletions src/main/java/org/petmarket/config/CachingConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package org.petmarket.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CachingConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("users");
}
}
2 changes: 2 additions & 0 deletions src/main/java/org/petmarket/users/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import org.petmarket.users.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -86,6 +87,7 @@ public boolean isCurrentUserAdmin() {
return auth != null && auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));
}

@Cacheable(value = "users", key = "#userId")
public User findById(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new ItemNotFoundException("User not found by id: " + userId));
Expand Down

0 comments on commit 90f103d

Please sign in to comment.