Skip to content

Commit

Permalink
feat: First Implementation of a Redis Cache
Browse files Browse the repository at this point in the history
  • Loading branch information
IsaacAndra committed Jan 12, 2025
1 parent 27da33a commit 34d0b81
Show file tree
Hide file tree
Showing 17 changed files with 117 additions and 12 deletions.
4 changes: 4 additions & 0 deletions src/main/java/com/isaacandrade/blog/BlogApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@Slf4j
@EnableCaching
@EnableScheduling
public class BlogApplication {

public static void main(String[] args) {
Expand Down
26 changes: 26 additions & 0 deletions src/main/java/com/isaacandrade/blog/config/CacheManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.isaacandrade.blog.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.time.Duration;

public class CacheManager {

@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() //
.prefixCacheNameWith(this.getClass().getPackageName() + ".") //
.entryTtl(Duration.ofSeconds(10)) //
.disableCachingNullValues();

return RedisCacheManager.builder(connectionFactory) //
.cacheDefaults(config) //
.build();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.isaacandrade.blog.config;

public class FileStorageConfig {
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public class PostController {
}
)
public ResponseEntity<List<PostDTO>> findAllPosts(){
List<PostDTO> posts = postService.findAllActives();
List<PostDTO> posts = postService.findAllActivesCache();
return ResponseEntity.ok(posts);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import com.isaacandrade.blog.domain.user.UserDTO;

import java.io.Serializable;
import java.util.List;

public record AuthorWithPostsDTO(UserDTO author, List<PostDTO> posts) {
public record AuthorWithPostsDTO(UserDTO author, List<PostDTO> posts) implements Serializable {
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package com.isaacandrade.blog.domain.post;


import java.io.Serializable;

public record CreatePostDTO(
String title,
String content,
Boolean isActive
) {
) implements Serializable {
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.isaacandrade.blog.domain.post;

import java.io.Serializable;

public record EditPostDTO(
String title,
String content
) {
) implements Serializable {
}
5 changes: 4 additions & 1 deletion src/main/java/com/isaacandrade/blog/domain/post/PostDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

import java.io.Serializable;
import java.time.LocalDateTime;


@JsonPropertyOrder({"id", "title", "content", "createdAt", "isActive"})
public record PostDTO(Long id, String title, String content, @JsonFormat(pattern = "dd/MM/yyyy HH:mm") LocalDateTime createdAt, Boolean isActive) {
public record PostDTO(Long id, String title, String content, @JsonFormat(pattern = "dd/MM/yyyy HH:mm") @JsonSerialize(using = LocalDateTimeSerializer.class)LocalDateTime createdAt, Boolean isActive) implements Serializable {
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

import com.fasterxml.jackson.annotation.JsonProperty;

import java.io.Serializable;

public record AuthenticationDTO(

@JsonProperty("username")
String userName,
@JsonProperty("senha")
String passWord
) {
) implements Serializable {
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Email;

import java.io.Serializable;

public record CreateUserDTO(
@JsonProperty("username")
String userName,
Expand All @@ -13,5 +15,5 @@ public record CreateUserDTO(
String passWord,

UserRole role
) {
) implements Serializable {
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import com.fasterxml.jackson.annotation.JsonProperty;

import java.io.Serializable;

public record EditUserDTO(
@JsonProperty("username")
String userName,
Expand All @@ -12,6 +14,6 @@ public record EditUserDTO(
@JsonProperty("role")
UserRole role

) {
) implements Serializable {

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
package com.isaacandrade.blog.domain.user;

public record LoginResponseDTO(String token) {
import java.io.Serializable;

public record LoginResponseDTO(String token) implements Serializable {
}
4 changes: 3 additions & 1 deletion src/main/java/com/isaacandrade/blog/domain/user/UserDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import jakarta.validation.constraints.Email;

import java.io.Serializable;

@JsonPropertyOrder({"id", "userName", "email"})
public record UserDTO(

Expand All @@ -19,5 +21,5 @@ public record UserDTO(
UserRole role


) {
) implements Serializable {
}
40 changes: 39 additions & 1 deletion src/main/java/com/isaacandrade/blog/service/PostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,20 @@
import com.isaacandrade.blog.exception.ConstraintViolationException;
import com.isaacandrade.blog.exception.PostNotFoundException;
import com.isaacandrade.blog.infra.exceptionhandler.ApplicationExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PostService {

Expand All @@ -26,6 +33,12 @@ public class PostService {
private ApplicationExceptionHandler exceptionHandler;


// Cacheamento
@Cacheable(value = "posts", key = "'findAllActivesCache'")
public List<PostDTO> findAllActivesCache(){
return findAllActives();
}

public List<PostDTO> findAllActives(){
List<Post> posts = postRepository.findByIsActiveTrue();
if (posts.isEmpty()){
Expand All @@ -34,6 +47,17 @@ public List<PostDTO> findAllActives(){
return posts.stream().map(this::mapToPostDTO).collect(Collectors.toList());
}


//Sistema de limpeza de cache dos Posts - 12 horas LIMPA
@Scheduled(fixedDelay = 12, timeUnit = TimeUnit.HOURS)
@CacheEvict("posts")
public void limparPostsCache() {
log.info("Cache de Posts Limpado!");
}



@Cacheable(value = "posts", key = "#authorId", unless = "#result == null")
public AuthorWithPostsDTO findPostsWithAuthorId(Long authorId){
UserDTO author = userService.findUserById(authorId);
List<Post> posts = postRepository.findPostsByAuthorId(authorId);
Expand All @@ -47,6 +71,9 @@ public AuthorWithPostsDTO findPostsWithAuthorId(Long authorId){
return new AuthorWithPostsDTO(author, postDTOs);
}



@Cacheable(value = "posts", key = "#title", unless = "#result == null")
public PostDTO findByTitle(String title){
Post posts = postRepository.findByTitle(title);
if (posts.getTitle().isEmpty()) {
Expand All @@ -55,6 +82,8 @@ public PostDTO findByTitle(String title){
return mapToPostDTO(posts);
}



public PostDTO createPost(CreatePostDTO data, Long authorId){
Post post = new Post();
UserDTO author = userService.findUserById(authorId);
Expand All @@ -73,6 +102,8 @@ public PostDTO createPost(CreatePostDTO data, Long authorId){
return mapToPostDTO(savedPost);
}

@CachePut(value = "posts", key = "#id")
@CacheEvict(value = "posts", key = "'findAllActivesCache'")
public PostDTO updatePost(Long id, EditPostDTO data){
Post post = postRepository.findById(id).orElseThrow(() -> new PostNotFoundException("Post With Id " + id + " Was Not Found"));
post.updatePost(data);
Expand All @@ -81,12 +112,17 @@ public PostDTO updatePost(Long id, EditPostDTO data){
return mapToPostDTO(post);
}



@CacheEvict(value = "posts", key = "#id")
public void deletePost(Long id){
Post post = postRepository.findById(id).orElseThrow(() -> new PostNotFoundException("Post With Id " + id + " Was Not Found"));
post.delete();
postRepository.save(post);
}



private User mapToUserEntity(UserDTO userDTO) {
User user = new User();
user.setId(userDTO.id());
Expand All @@ -95,6 +131,8 @@ private User mapToUserEntity(UserDTO userDTO) {
return user;
}



private PostDTO mapToPostDTO(Post post) {
UserDTO authorDTO = new UserDTO(post.getAuthor().getId(), post.getAuthor().getEmail(), post.getAuthor().getUsername(), post.getAuthor().getRole());
return new PostDTO(
Expand All @@ -105,4 +143,4 @@ private PostDTO mapToPostDTO(Post post) {
post.getIsActive()
);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
import com.isaacandrade.blog.exception.ConstraintViolationException;
import com.isaacandrade.blog.exception.ProjectNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
Expand All @@ -26,6 +29,7 @@ public class ProjectService {
TechnologyRepository technologyRepository;

// Metodo que para listar todos os projetos
@Cacheable(value = "projects", key = "#id", unless = "#result == null")
public List<ProjectDto> getAllProjects() {
List<Project> projects = projectRepository.findAll();
if (projects.isEmpty()){
Expand All @@ -35,6 +39,7 @@ public List<ProjectDto> getAllProjects() {
}

// Metodo para mostrar um projeto pelo id
@Cacheable(value = "projects", key = "#name", unless = "#result.name == null")
public ProjectDto getProjectByName(String name) {
Project project = projectRepository.findByName(name);

Expand Down Expand Up @@ -82,6 +87,8 @@ public ProjectDto createProject(CreateProjectDto data) {
return mapToProjectDTO(projectRepository.save(project));
}


@CachePut(value = "projects", key = "#id")
public Optional<ProjectDto> updateProject(Long id, CreateProjectDto data) {

projectRepository.findById(id).orElseThrow(() ->
Expand Down Expand Up @@ -124,6 +131,7 @@ public Optional<ProjectDto> updateProject(Long id, CreateProjectDto data) {
});
}

@CacheEvict(value = "projects", key = "#id")
public void deleteProject(Long id) {

projectRepository.findById(id).orElseThrow(() -> new ProjectNotFoundException("Project With id " + id + " Was Not Found!"));
Expand Down
8 changes: 8 additions & 0 deletions src/main/resources/application-prod.properties
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,11 @@ spring.flyway.clean-disabled=false
springdoc.pathsToMatch=/**/**/**
springdoc.swagger-ui.use-root-path=true


spring.redis.host=redis
spring.redis.port=6379
spring.cache.type=redis

spring.data.redis.repositories.enabled=false
logging.level.org.springframework.cache=trace

2 changes: 1 addition & 1 deletion src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
spring.profiles.active=prod
spring.profiles.active=dev

0 comments on commit 34d0b81

Please sign in to comment.