Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[신윤섭] 5차 과제 제출 #28

Open
wants to merge 26 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
6c986fe
:sparkles: feat: Post 엔티티 구현
supsup-hae Nov 9, 2024
e74f4ff
:truck: rename: 디렉토리 구조 수정 및 패키지 이동
supsup-hae Nov 9, 2024
4b28a5d
:see_no_evil: chore: .gitignore 수정
supsup-hae Nov 15, 2024
40a1c4a
:recycle: refactor: Dto 클래스를 record 클래스로 변환
supsup-hae Nov 16, 2024
d9756c0
:truck: refactor: repository 패키지 위치 변경
supsup-hae Nov 16, 2024
e3c205b
:sparkles: feat: 게시글 단일 생성 기능 구현 및 서비스 로직 변경
supsup-hae Nov 16, 2024
1066d7f
:recycle: refactor: Batch Insert를 위한 기본 키 생성 전략 변경
supsup-hae Nov 17, 2024
77a5bed
:sparkles: feat: Batch Insert를 이용한 게시글 다중 생성 기능 구현
supsup-hae Nov 17, 2024
d2d1746
:sparkles: feat: 게시글 조회 및 조회수 증가 기능 구현
supsup-hae Nov 17, 2024
1b29745
:recycle: refactor: 메서드명 변경
supsup-hae Nov 17, 2024
8a73a05
:sparkles: feat: Pageable 구현을 위한 Response 객체 생성
supsup-hae Nov 17, 2024
9f3aecf
:sparkles: feat: Post 엔티티에 likes 필드 추가
supsup-hae Nov 17, 2024
f699938
:sparkles: feat: 게시글 목록 조회 기능 구현
supsup-hae Nov 17, 2024
67118a1
:sparkles: feat: 게시글 삭제 기능 구현
supsup-hae Nov 17, 2024
3f03a4a
:sparkles: feat: 게시물 삭제 예외 처리 기능 구현
supsup-hae Nov 21, 2024
e35e93b
:recycle: refactor: PostController의 RESTful API 설계 개선
supsup-hae Nov 21, 2024
cc1af40
:recycle: refactor: 매직넘버 상수 처리
supsup-hae Nov 21, 2024
df24e3d
:sparkles: feat: 네임드 락을 이용한 동시성 문제 해결
supsup-hae Dec 23, 2024
15af1a5
:sparkles: feat: 조회 성능 향상을 위한 인덱싱 도입
supsup-hae Dec 23, 2024
3b26072
:recycle: refactor: Validation 형식 변경
supsup-hae Dec 23, 2024
c8921a3
:recycle: refactor: Response DTO 네이밍 변경
supsup-hae Dec 23, 2024
a122045
:truck: refactor: Response DTO 패키지 이동
supsup-hae Dec 23, 2024
f4e5982
:recycle: refactor: Post 도메인 에러 코드 작성 및 적용
supsup-hae Dec 23, 2024
0d58f4e
:sparkles: feat: 서비스 로깅 기능 추가
supsup-hae Dec 23, 2024
9b1da8d
:recycle: refactor: 불필요 코드 리팩터링 진행
supsup-hae Dec 26, 2024
8d9867a
:sparkles: feat: 조회 로직 cache 적용 및 구현
supsup-hae Jan 9, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ build/
!**/src/main/**/build/
!**/src/test/**/build/

### Properties Files ###
src/main/resources/application.properties
src/main/resources/application-*.properties
*.properties
!gradle.properties

### STS ###
.apt_generated
.classpath
Expand Down
1 change: 1 addition & 0 deletions backend/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.mysql:mysql-connector-j'
Expand Down
2 changes: 2 additions & 0 deletions backend/src/main/java/cotato/backend/BackendApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@EnableCaching
@SpringBootApplication
public class BackendApplication {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package cotato.backend.common.config;

import java.util.List;

import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(List.of(
new ConcurrentMapCache("posts")
));
return cacheManager;
}
}

37 changes: 37 additions & 0 deletions backend/src/main/java/cotato/backend/common/dto/PageResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package cotato.backend.common.dto;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;

import com.fasterxml.jackson.annotation.JsonInclude;

import lombok.Getter;

@Getter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PageResponse<T> extends BaseResponse {
private final List<T> items;
private final int currentPage;
private final int totalPages;
private final long totalItems;

private PageResponse(HttpStatus status, List<T> content, int number, int totalPages, long totalElements) {
super(status);
this.items = content;
this.currentPage = number;
this.totalPages = totalPages;
this.totalItems = totalElements;
}

public static <T> PageResponse<T> from(Page<T> page) {
return new PageResponse<>(
HttpStatus.OK,
page.getContent(),
page.getNumber(),
page.getTotalPages(),
page.getTotalElements()
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,14 @@ public enum ErrorCode {
BAD_REQUEST(HttpStatus.BAD_REQUEST, "잘못된 요청입니다.", "COMMON-001"),
INVALID_PARAMETER(HttpStatus.BAD_REQUEST, "요청 파라미터가 잘 못 되었습니다.", "COMMON-002"),

//POST-400
POST_NOT_FOUND(HttpStatus.NOT_FOUND,"게시물을 찾지 못했습니다." , "COMMON-003" ),
POST_DELETE_FAILED(HttpStatus.BAD_REQUEST,"게시물 삭제가 실패하였습니다." , "COMMON-004" ),
POST_SAVE_FAILED(HttpStatus.BAD_REQUEST,"게시물 저장을 실패하였습니다." , "COMMON-005" ),

//500
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "서버 내부에서 에러가 발생하였습니다.", "COMMON-002"),
;
CONCURRENCY_PROBLEM(HttpStatus.INTERNAL_SERVER_ERROR, "동시성 에러가 발생하였습니다." , "COMMON-003");

private final HttpStatus httpStatus;
private final String message;
Expand Down
13 changes: 0 additions & 13 deletions backend/src/main/java/cotato/backend/domains/post/Post.java

This file was deleted.

This file was deleted.

42 changes: 0 additions & 42 deletions backend/src/main/java/cotato/backend/domains/post/PostService.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package cotato.backend.domains.post.controller;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cotato.backend.common.dto.DataResponse;
import cotato.backend.common.dto.PageResponse;
import cotato.backend.domains.post.dto.response.PostResponse;
import cotato.backend.domains.post.dto.request.SavePostsByExcelRequest;
import cotato.backend.domains.post.dto.request.SaveSinglePostRequest;
import cotato.backend.domains.post.service.PostServiceImpl;
import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/api/posts")
@RequiredArgsConstructor
public class PostController {

private final PostServiceImpl postService;

@PostMapping("/excel")
public ResponseEntity<DataResponse<Void>> savePostsByExcel(@RequestBody SavePostsByExcelRequest request) {
postService.saveEstatesByExcel(request);
return ResponseEntity.ok(DataResponse.ok());
}

@PostMapping
public ResponseEntity<DataResponse<Void>> savePost(@RequestBody SaveSinglePostRequest request) {
postService.saveSinglePost(request);
return ResponseEntity.ok(DataResponse.ok());
}

@GetMapping("/{id}")
public ResponseEntity<DataResponse<PostResponse>> getPost(@PathVariable Long id) {
return ResponseEntity.ok(DataResponse.from(postService.findPostById(id)));
}

@GetMapping
public ResponseEntity<PageResponse<PostResponse>> getPopularPosts(
@PageableDefault(sort = "likes", direction = Sort.Direction.DESC) Pageable pageable) {
return ResponseEntity.ok(PageResponse.from(postService.findPostsSortedByLikes(pageable)));
}

@DeleteMapping("/{id}")
public ResponseEntity<DataResponse<Void>> deletePost(@PathVariable Long id) {
postService.deletePostById(id);
return ResponseEntity.ok(DataResponse.ok());
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,4 @@
package cotato.backend.domains.post.dto.request;

import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SavePostsByExcelRequest {

private String path;
public record SavePostsByExcelRequest(String path) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package cotato.backend.domains.post.dto.request;

import cotato.backend.domains.post.entity.Post;
import jakarta.validation.constraints.NotBlank;

public record SaveSinglePostRequest(@NotBlank(message = "Title은 공백일 수 없습니다.") String title,
@NotBlank(message = "Content는 공백일 수 없습니다.") String content,
@NotBlank(message = "Name은 공백일 수 없습니다.") String name) {

public Post toEntity() {
return Post.builder().
title(title).
content(content).
name(name).
build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package cotato.backend.domains.post.dto.response;

import cotato.backend.domains.post.entity.Post;
import lombok.Builder;
import lombok.NonNull;

@Builder
public record PostResponse(@NonNull String title, @NonNull String content, @NonNull String name, int views, int likes) {

public static PostResponse from(Post post) {
return new PostResponse(post.getTitle(), post.getContent(), post.getName(), post.getViews(), post.getLikes());
}
}
63 changes: 63 additions & 0 deletions backend/src/main/java/cotato/backend/domains/post/entity/Post.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package cotato.backend.domains.post.entity;

import org.hibernate.annotations.ColumnDefault;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.Table;
import jakarta.persistence.Version;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Table(name = "post",
indexes = {
@Index(name = "idx_post_views", columnList = "views")
}
)
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NonNull
private String title;

@NonNull
private String content;

@NonNull
private String name;

@ColumnDefault("0")
private int views;

@ColumnDefault("0")
private int likes;

@Version
@Column(name = "version", columnDefinition = "bigint default 0")
private Long version = 0L;

@Builder
public Post(String title, String content, String name, int views, int likes) {
this.title = title;
this.content = content;
this.name = name;
this.views = views;
this.likes = likes;
}

public void increaseViews() {
this.views++;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package cotato.backend.domains.post.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import cotato.backend.domains.post.entity.Post;

@Repository
public interface LockRepository extends JpaRepository<Post, Long> {
@Query(value = "select get_lock(:key, 3000)", nativeQuery = true)
void getLock(String key);

@Query(value = "select release_lock(:key)", nativeQuery = true)
void releaseLock(String key);
}
Loading