Skip to content

Commit

Permalink
[fix] DB indexing + Category Caching
Browse files Browse the repository at this point in the history
  • Loading branch information
gwon477 committed Feb 12, 2024
1 parent 9985f26 commit 6e72bca
Show file tree
Hide file tree
Showing 13 changed files with 40 additions and 21 deletions.
4 changes: 2 additions & 2 deletions src/main/java/com/dmarket/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,8 @@ public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
.authorizeHttpRequests((auth) -> auth
.requestMatchers("/", "/api/users/login", "/api/users/email/**", "/api/users/join").permitAll()
// .requestMatchers("/api/admin/**").hasAnyRole("GM", "SM", "PM")
// .anyRequest().authenticated());
.anyRequest().permitAll());
.anyRequest().authenticated());
// .anyRequest().permitAll());


// 커스텀 필터 적용
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/com/dmarket/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ public ResponseEntity<?> getWishlistByUserId(@PathVariable(name = "userId") Long
// 장바구니 상품 개수 조회
@GetMapping("{userId}/cart-count")
public ResponseEntity<?> getCartCount(@PathVariable(name = "userId") Long userId, HttpServletRequest request) {
System.out.println("userId = " + userId);
ResponseEntity<CMResDto<String>> authorization = checkAuthorization(userId, request);
if(authorization != null){
return authorization;
Expand Down Expand Up @@ -197,11 +198,16 @@ public ResponseEntity<?> updateAddress(HttpServletRequest request,
// 장바구니 조회
@GetMapping("/{userId}/cart")
public ResponseEntity<?> getCarts(@PathVariable Long userId, HttpServletRequest request) {
System.out.println("test.A");
System.out.println("userId = " + userId);
System.out.println("request = " + request);
// 권한 검증 메서드
ResponseEntity<CMResDto<String>> authorization = checkAuthorization(userId, request);
if(authorization != null){
System.out.println("test.B");
return authorization;
}
System.out.println("test.C");
List<CartCommonDto.CartListDto> cartListDtos = userService.getCartsFindByUserId(userId);
CartResDto.TotalCartResDto totalCartResDto = new CartResDto.TotalCartResDto(cartListDtos);
return new ResponseEntity<>(CMResDto.successDataRes(totalCartResDto), HttpStatus.OK);
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/com/dmarket/domain/product/Category.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,10 @@ public class Category {

@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
private List<Category> child = new ArrayList<>();

public class RedisCacheKey {

public static final String CATEGORY_LIST = "categoryList";
public static final String PRODUCT_LIST = "productList";
}
}
1 change: 1 addition & 0 deletions src/main/java/com/dmarket/domain/product/Product.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Table(indexes = @Index(name = "idx_category_id", columnList = "category_id"))
public class Product {

@Id
Expand Down
1 change: 1 addition & 0 deletions src/main/java/com/dmarket/domain/product/ProductImgs.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Table(indexes = @Index(name = "idx_product_id", columnList = "product_id"))
public class ProductImgs {

@Id
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Table(indexes = @Index(name = "idx_product_id", columnList = "product_id"))
public class ProductOption {

@Id
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Table(indexes = @Index(name = "idx_product_id", columnList = "product_id"))
public class ProductReview {

@Id
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public ResponseEntity<CMResDto<String>> handleConflictException(ConflictExceptio
// 위의 경우를 제외한 모든 에러 500
@ExceptionHandler(Exception.class)
public ResponseEntity<CMResDto<String>> handleException(Exception e) {
log.error("[Exception] message: {}", e.getMessage());
log.error("[Exception] message: {},{}", e.getMessage(), e.getClass(), e.getCause());
ErrorCode errorCode = ErrorCode.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(CMResDto.errorRes(errorCode), HttpStatus.INTERNAL_SERVER_ERROR);
}
Expand Down
6 changes: 4 additions & 2 deletions src/main/java/com/dmarket/jwt/JWTFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse

//request에서 Authorization 헤더를 찾음
String authorization = request.getHeader("Authorization");
System.out.println("authorization = " + authorization);

//Authorization 헤더 검증
if (authorization == null || !authorization.startsWith("Bearer ")) {
Expand Down Expand Up @@ -91,6 +92,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse

//토큰에서 정보 추출
String type = jwtUtil.getType(token);
System.out.println("type = " + type);
String email = jwtUtil.getEmail(token);
String role = jwtUtil.getRole(token);
Long tokenUserId = jwtUtil.getUserId(token);
Expand All @@ -102,15 +104,15 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
if (refreshTokenRepository.existsById(token)) {
refreshTokenRepository.deleteById(token);
String newAccessToken = jwtUtil.createAccessJwt(tokenUserId, email, role);
String newRefreshToken = jwtUtil.createRefreshJwt();
String newRefreshToken = jwtUtil.createRefreshJwt(tokenUserId);
refreshTokenRepository.save(new RefreshToken(newRefreshToken, newAccessToken, email));

UserCommonDto.TokenResponseDto tokenResponseDto = new UserCommonDto.TokenResponseDto(newAccessToken, newRefreshToken, tokenUserId, role);

CMResDto<UserCommonDto.TokenResponseDto> cmRespDto = CMResDto.<UserCommonDto.TokenResponseDto>builder()
.code(200)
.msg("새로운 토큰 발급 Success")
//.data(tokenResponseDto)
.data(tokenResponseDto)
.build();

writeResponse(response, cmRespDto);
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/dmarket/jwt/JWTUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,9 @@ public String createAccessJwt(Long userId, String email, String role) {
.compact();
}

public String createRefreshJwt() {
public String createRefreshJwt(Long userId) {
return Jwts.builder()
.claim("userId",userId)
.claim("type", "RTK")
.issuedAt(new Date(System.currentTimeMillis()))
.expiration(new Date(System.currentTimeMillis() + 240 * 60 * 60 * 1000))
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/dmarket/jwt/LoginFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ protected void successfulAuthentication(HttpServletRequest request, HttpServletR
String accesstoken = jwtUtil.createAccessJwt(userId, email, role);

// RefreshToken 만료 시간 240시간
String refreshtoken = jwtUtil.createRefreshJwt();
String refreshtoken = jwtUtil.createRefreshJwt(userId);

refreshTokenRepository.save(new RefreshToken(refreshtoken, accesstoken, email));

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/dmarket/service/AdminService.java
Original file line number Diff line number Diff line change
Expand Up @@ -811,7 +811,7 @@ public UserCommonDto.TokenResponseDto changeRole(Long userId, UserReqDto.ChangeR

// 토큰 재발급
String newaccessToken = jwtUtil.createAccessJwt(userId, newRole.getNewRole(), user.getUserEmail());
String newrefreshToken = jwtUtil.createRefreshJwt();
String newrefreshToken = jwtUtil.createRefreshJwt(userId);

return new UserCommonDto.TokenResponseDto(newaccessToken, newrefreshToken, userId, newRole.toString());
}
Expand Down
26 changes: 13 additions & 13 deletions src/main/java/com/dmarket/service/ProductService.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@
import com.dmarket.exception.BadRequestException;
import com.dmarket.exception.NotFoundException;
import com.dmarket.repository.product.*;
import com.dmarket.repository.user.UserRepository;
import com.dmarket.repository.user.WishlistRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
Expand All @@ -36,7 +39,9 @@ public class ProductService {
// 조회가 아닌 메서드들은 꼭 @Transactional 넣어주세요 (CUD, 입력/수정/삭제)
private final CategoryRepository categoryRepository;
private final ProductRepository productRepository;
private final UserRepository userRepository;
private final QnaRepository qnaRepository;
private final WishlistRepository wishlistRepository;
private final ProductImgsRepository productImgsRepository;
private final ProductOptionRepository productOptionRepository;
private final ProductReviewRepository productReviewRepository;
Expand All @@ -47,11 +52,8 @@ public class ProductService {
private static final int REVIEW_PAGE_POST_COUNT = 5;
private static final Integer MAX_VALUE = 9999999;


/**
* 카테고리: Category
*/
// 카테고리 전체 목록 depth별로 조회
@Cacheable(value = Category.RedisCacheKey.CATEGORY_LIST, key = "#categoryDepthLevel", cacheManager = "redisCacheManager") // 캐시 적용, 캐시 키 설정, 캐시 저장 기간
public List<CategoryResDto.CategoryListResDto> getCategories(Integer categoryDepthLevel) {
return categoryRepository.findByCategoryDepth(categoryDepthLevel);
}
Expand All @@ -76,7 +78,9 @@ public Product findProductById(Long productId) {
}

// 카테고리별 상품 목록 필터링 조회
public Page<ProductResDto.ProductListResDto> getCategoryProducts(int pageNo, Long cateId, String sorter, Integer minPrice, Integer maxPrice, Float star) {
//@Cacheable(value = Category.RedisCacheKey.PRODUCT_LIST, key = "#productItemList", cacheManager = "redisCacheManager")
public Page<ProductResDto.ProductListResDto> getCategoryProducts(int pageNo, Long cateId,
String sorter, Integer minPrice, Integer maxPrice, Float star) {
findCategoryById(cateId);
sorter = sorterValidation(sorter);
pageNo = pageValidation(pageNo);
Expand All @@ -89,7 +93,8 @@ public Page<ProductResDto.ProductListResDto> getCategoryProducts(int pageNo, Lon
}

// 상품 목록 조건 검색
public Page<ProductResDto.ProductListResDto> getSearchProducts(int pageNo, String query, String sorter, Integer minPrice, Integer maxPrice, Float star) {
public Page<ProductResDto.ProductListResDto> getSearchProducts(int pageNo, String query,
String sorter, Integer minPrice, Integer maxPrice, Float star) {
if (query.isEmpty()) {
throw new BadRequestException(INVALID_SEARCH_VALUE);
}
Expand Down Expand Up @@ -163,21 +168,17 @@ public List<Object> mapToResponseFormat(List<ProductResDto.NewProductResDto> lat
public ProductResDto.ProductInfoResDto getProductInfo(Long productId) {

// 싱품 정보 조회
Product product = findProductById(productId);

Product product = productRepository.findById(productId)
.orElseThrow(() -> new IllegalArgumentException("존재하지 않는 상품입니다."));
// 상품의 카테고리 depth 1, depth2 조회 후 합치기
Category category = categoryRepository.findByCategoryId(product.getCategoryId());
String productCategory = category.getParent().getCategoryName() + " > " + category.getCategoryName();

// 상품의 리뷰 개수 조회
Long reviewCnt = productReviewRepository.countByProductId(productId);

// 상품 옵션 목록, 옵션별 재고 조회
List<ProductCommonDto.ProductOptionDto> opts = productOptionRepository.findOptionsByProductId(productId);

// 상품 이미지 목록 조회
List<String> imgs = productImgsRepository.findAllByProductId(productId);

// DTO 생성 및 반환
return new ProductResDto.ProductInfoResDto(product, productCategory, reviewCnt, opts, imgs);
}
Expand Down Expand Up @@ -269,7 +270,6 @@ public void saveReview(ReviewReqDto reviewReqDto, Long productId) {
.reviewImg(reviewReqDto.getReviewImg())
.build();
productReviewRepository.save(productReview);

// 상품 정보에 별점 반영
updateProductRating(productId, reviewReqDto.getReviewRating());
}
Expand Down

0 comments on commit 6e72bca

Please sign in to comment.