Skip to content

Commit

Permalink
Merge pull request #207 from dionisos198/Refactor/#205-community-post…
Browse files Browse the repository at this point in the history
…-performance

Refactor/#205 community post performance
  • Loading branch information
dionisos198 authored Oct 24, 2024
2 parents 29af594 + a79c695 commit c79be3a
Show file tree
Hide file tree
Showing 4 changed files with 111 additions and 131 deletions.
Original file line number Diff line number Diff line change
@@ -1,90 +1,90 @@
package com.gaduationproject.cre8.app.apitest;

import com.gaduationproject.cre8.common.response.error.ErrorCode;
import com.gaduationproject.cre8.common.response.error.exception.NotFoundException;
import com.gaduationproject.cre8.domain.community.entity.CommunityBoard;
import com.gaduationproject.cre8.domain.community.entity.CommunityPost;
import com.gaduationproject.cre8.domain.community.repository.CommunityBoardRepository;
import com.gaduationproject.cre8.domain.community.repository.CommunityPostRepository;
import com.gaduationproject.cre8.domain.member.entity.Member;
import com.gaduationproject.cre8.domain.member.repository.MemberRepository;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@RequiredArgsConstructor
@Component
public class CommunityPostInitializer implements ApplicationRunner {

private final CommunityPostRepository communityPostRepository;
private final CommunityBoardRepository communityBoardRepository;
private final MemberRepository memberRepository;
private final JdbcTemplate jdbcTemplate;

@Override
public void run(ApplicationArguments args) throws Exception {

List<CommunityPost> communityPosts = new ArrayList<>();

Member member = memberRepository.findMemberByLoginId("dionisos198").orElseThrow(()-> new NotFoundException(ErrorCode.CANT_FIND_MEMBER));
CommunityBoard communityBoard = communityBoardRepository.findById(1L).orElseThrow(()-> new NotFoundException(ErrorCode.CANT_FIND_COMMUNITY_BOARD));



//10만건의 Member 데이터를 저장한다.
for(int i=0;i<50000;i++) {

CommunityPost communityPost = CommunityPost.builder()
.communityBoard(communityBoard)
.title("테스트 커뮤니티 제목")
.accessUrl("www.")
.contents("테스트 커뮤니티 콘텐츠입니당")
.writer(member)
.build();

System.out.println("현재 i:" + i);
communityPosts.add(communityPost);

if (i % 5000 == 0) {
String sql =
"INSERT INTO community_post (contents,title,community_board_id,writer_id) "
+ "VALUES (?,?,?,?)";
// jdbc 의 batch 를 이용해서 직접 대용량의 데이터를 저장한다. (GenerationType.Identity이므로)
jdbcTemplate.batchUpdate(sql,
communityPosts, communityPosts.size(),
(PreparedStatement ps, CommunityPost communityPost1) -> {
ps.setString(1, communityPost1.getContents());
ps.setString(2, communityPost1.getTitle());
ps.setLong(3, communityPost1.getCommunityBoard().getId());
ps.setLong(4, communityPost1.getWriter().getId());
});

communityPosts.clear();
}
}
String sql =
"INSERT INTO community_post (contents,title,community_board_id,writer_id) "
+ "VALUES (?,?,?,?)";
// jdbc 의 batch 를 이용해서 직접 대용량의 데이터를 저장한다. (GenerationType.Identity이므로)
jdbcTemplate.batchUpdate(sql,
communityPosts, communityPosts.size(),
(PreparedStatement ps, CommunityPost communityPost1) -> {
ps.setString(1, communityPost1.getContents());
ps.setString(2, communityPost1.getTitle());
ps.setLong(3, communityPost1.getCommunityBoard().getId());
ps.setLong(4, communityPost1.getWriter().getId());
});

communityPosts.clear();


}


}
//package com.gaduationproject.cre8.app.apitest;
//
//import com.gaduationproject.cre8.common.response.error.ErrorCode;
//import com.gaduationproject.cre8.common.response.error.exception.NotFoundException;
//import com.gaduationproject.cre8.domain.community.entity.CommunityBoard;
//import com.gaduationproject.cre8.domain.community.entity.CommunityPost;
//import com.gaduationproject.cre8.domain.community.repository.CommunityBoardRepository;
//import com.gaduationproject.cre8.domain.community.repository.CommunityPostRepository;
//import com.gaduationproject.cre8.domain.member.entity.Member;
//import com.gaduationproject.cre8.domain.member.repository.MemberRepository;
//import java.sql.PreparedStatement;
//import java.util.ArrayList;
//import java.util.List;
//import lombok.RequiredArgsConstructor;
//import org.springframework.boot.ApplicationArguments;
//import org.springframework.boot.ApplicationRunner;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.jdbc.core.JdbcTemplate;
//import org.springframework.stereotype.Component;
//
//@RequiredArgsConstructor
//@Component
//public class CommunityPostInitializer implements ApplicationRunner {
//
// private final CommunityPostRepository communityPostRepository;
// private final CommunityBoardRepository communityBoardRepository;
// private final MemberRepository memberRepository;
// private final JdbcTemplate jdbcTemplate;
//
// @Override
// public void run(ApplicationArguments args) throws Exception {
//
// List<CommunityPost> communityPosts = new ArrayList<>();
//
// Member member = memberRepository.findMemberByLoginId("dionisos198").orElseThrow(()-> new NotFoundException(ErrorCode.CANT_FIND_MEMBER));
// CommunityBoard communityBoard = communityBoardRepository.findById(1L).orElseThrow(()-> new NotFoundException(ErrorCode.CANT_FIND_COMMUNITY_BOARD));
//
//
//
////10만건의 Member 데이터를 저장한다.
// for(int i=0;i<50000;i++) {
//
// CommunityPost communityPost = CommunityPost.builder()
// .communityBoard(communityBoard)
// .title("테스트 커뮤니티 제목")
// .accessUrl("www.")
// .contents("테스트 커뮤니티 콘텐츠입니당")
// .writer(member)
// .build();
//
// System.out.println("현재 i:" + i);
// communityPosts.add(communityPost);
//
// if (i % 5000 == 0) {
// String sql =
// "INSERT INTO community_post (contents,title,community_board_id,writer_id) "
// + "VALUES (?,?,?,?)";
//// jdbc 의 batch 를 이용해서 직접 대용량의 데이터를 저장한다. (GenerationType.Identity이므로)
// jdbcTemplate.batchUpdate(sql,
// communityPosts, communityPosts.size(),
// (PreparedStatement ps, CommunityPost communityPost1) -> {
// ps.setString(1, communityPost1.getContents());
// ps.setString(2, communityPost1.getTitle());
// ps.setLong(3, communityPost1.getCommunityBoard().getId());
// ps.setLong(4, communityPost1.getWriter().getId());
// });
//
// communityPosts.clear();
// }
// }
// String sql =
// "INSERT INTO community_post (contents,title,community_board_id,writer_id) "
// + "VALUES (?,?,?,?)";
//// jdbc 의 batch 를 이용해서 직접 대용량의 데이터를 저장한다. (GenerationType.Identity이므로)
// jdbcTemplate.batchUpdate(sql,
// communityPosts, communityPosts.size(),
// (PreparedStatement ps, CommunityPost communityPost1) -> {
// ps.setString(1, communityPost1.getContents());
// ps.setString(2, communityPost1.getTitle());
// ps.setLong(3, communityPost1.getCommunityBoard().getId());
// ps.setLong(4, communityPost1.getWriter().getId());
// });
//
// communityPosts.clear();
//
//
// }
//
//
//}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
"/api/v1/*/profile","/api/v1/members/pk","/api/v1/portfolios/*","/api/v1/portfolios/member/*","/api/v1/tags",
"/api/v1/tags/subcategory/*","/api/v1/tags/child/*","/api/v1/employer-posts/search","/api/v1/employee-posts/search",
"/api/v1/employer-posts/search/keyword","/api/v1/employee-posts/search/keyword","/api/v1/employee-posts/search/test","/api/v1/employer-posts/search/test",
"/api/v1/community/boards","/api/v1/community/posts/search/*","/api/v1/community/posts/*","/api/v1/community/posts/search/test/*").permitAll()
"/api/v1/community/boards","/api/v1/community/posts/search/*","/api/v1/community/posts/*").permitAll()
.requestMatchers(HttpMethod.POST,"/api/v1/test","/api/v1/redis/test","/api/v1/auth/login","/api/v1/mail",
"/api/v1/mail/check","/api/v1/members","/api/v1/mail/temp/password").permitAll()
.requestMatchers("/ws-stomp").permitAll()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,26 +34,6 @@ public class CommunityPostSearchController {

@GetMapping("/{communityBoardId}")
@Operation(summary = "커뮤니티 게시글 리스트",description = "커뮤니티 게시글을 커뮤니티 게시판 최신순으로 조회할 수 있습니다. ")
@ApiResponses(value = {
@ApiResponse(responseCode = "200",description = "커뮤니티 게시글 리스트 조회 성공")
})
@Parameters({
@Parameter(name = "page", description = "페이지 번호(0부터 시작)", in = ParameterIn.QUERY),
@Parameter(name = "direction", description = "내림차순과 오름차순(desc,asc)", in = ParameterIn.QUERY),
@Parameter(name = "sort", description = "정렬기준(createdAt)", in = ParameterIn.QUERY),
@Parameter(name = "size", description = "페이지당 아이템 갯수", in = ParameterIn.QUERY)
}
)
public ResponseEntity<BaseResponse<CommunityPostSearchWithSliceResponseDto>> communityPostSearchResponse(
@PathVariable("communityBoardId") final Long communityBoardId,
@PageableDefault(size = 10,sort = "createdAt",direction = Direction.DESC,page = 0) final Pageable pageable) {

return ResponseEntity.ok(BaseResponse
.createSuccess(communityPostSearchService.searchCommunityPostByCommunityBoardId(communityBoardId,pageable)));
}

@GetMapping("/test/{communityBoardId}")
@Operation(summary = "커뮤니티 게시글 리스트2",description = "커뮤니티 게시글을 커뮤니티 게시판 최신순으로 조회할 수 있습니다.2 ")
@ApiResponses(value = {
@ApiResponse(responseCode = "200",description = "커뮤니티 게시글 리스트 조회 성공2")
})
Expand All @@ -64,7 +44,7 @@ public ResponseEntity<BaseResponse<CommunityPostSearchWithSliceResponseDto>> com
@Parameter(name = "size", description = "페이지당 아이템 갯수", in = ParameterIn.QUERY)
}
)
public ResponseEntity<BaseResponse<CommunityPostSearchWithSliceResponseDto>> communityPostSearchResponse2(
public ResponseEntity<BaseResponse<CommunityPostSearchWithSliceResponseDto>> communityPostSearchResponse(
@PathVariable("communityBoardId") final Long communityBoardId,
@RequestParam(value = "lastPostId",required = false) final Long lastPostId,
@PageableDefault(size = 10,sort = "createdAt",direction = Direction.DESC,page = 0) final Pageable pageable) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,25 +37,25 @@ public class CommunityPostSearchService {
private final LikeCommunityPostRepository likeCommunityPostRepository;


public CommunityPostSearchWithSliceResponseDto searchCommunityPostByCommunityBoardId(final Long communityBoardId,
final Pageable pageable){

Slice<CommunityPostSearchDBResponseDto> communityPosts =
communityPostRepository.findCommunityPostKeyWordSearchDBByCommunityBoardId(communityBoardId,pageable);


List<CommunityPostSearchResponseDto> communityPostSearchResponseDtoList =
communityPosts.stream().map(communityPostSearchDBResponseDto -> {
return CommunityPostSearchResponseDto.of(communityPostSearchDBResponseDto.getCommunityPostId(),
communityPostSearchDBResponseDto.getTitle(),
replyRepository.totalReplyCount(communityPostSearchDBResponseDto.getCommunityPostId()),
communityPostSearchDBResponseDto.getWriterNickName(),
communityPostSearchDBResponseDto.getCreatedAt());
}).collect(Collectors.toList());

return CommunityPostSearchWithSliceResponseDto.of(communityPostSearchResponseDtoList,communityPosts.hasNext());

}
// public CommunityPostSearchWithSliceResponseDto searchCommunityPostByCommunityBoardId(final Long communityBoardId,
// final Pageable pageable){
//
// Slice<CommunityPostSearchDBResponseDto> communityPosts =
// communityPostRepository.findCommunityPostKeyWordSearchDBByCommunityBoardId(communityBoardId,pageable);
//
//
// List<CommunityPostSearchResponseDto> communityPostSearchResponseDtoList =
// communityPosts.stream().map(communityPostSearchDBResponseDto -> {
// return CommunityPostSearchResponseDto.of(communityPostSearchDBResponseDto.getCommunityPostId(),
// communityPostSearchDBResponseDto.getTitle(),
// replyRepository.totalReplyCount(communityPostSearchDBResponseDto.getCommunityPostId()),
// communityPostSearchDBResponseDto.getWriterNickName(),
// communityPostSearchDBResponseDto.getCreatedAt());
// }).collect(Collectors.toList());
//
// return CommunityPostSearchWithSliceResponseDto.of(communityPostSearchResponseDtoList,communityPosts.hasNext());
//
// }

public CommunityPostSearchWithSliceResponseDto searchCommunityPostByCommunityBoardIdAndLastPostId(final Long communityBoardId,
final Long lastPostId, final Pageable pageable){
Expand Down

0 comments on commit c79be3a

Please sign in to comment.