Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ configurations {

repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}

dependencies {
Expand Down Expand Up @@ -65,6 +66,9 @@ dependencies {
implementation 'io.jsonwebtoken:jjwt-impl:0.11.5'
// JWT JSON 처리(Jackson 연동)
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5'

// KOMORAN 형태소 분석
implementation 'com.github.shin285:KOMORAN:3.3.4'
}

tasks.named('test') {
Expand Down
7 changes: 6 additions & 1 deletion mysql-docker/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,12 @@ services:
- redis-data:/data
networks:
- bookshop-network
command: redis-server --appendonly yes
command: >
redis-server
--appendonly yes
--maxmemory 512mb
--maxmemory-policy volatile-lru
--maxmemory-samples 5

flyway:
image: flyway/flyway:9.22.3
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.fastcampus.book_bot.common.config;

import kr.co.shineware.nlp.komoran.constant.DEFAULT_MODEL;
import kr.co.shineware.nlp.komoran.core.Komoran;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class KomoranConfig {

@Bean
public Komoran komoran() {
return new Komoran(DEFAULT_MODEL.FULL);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

Expand All @@ -19,20 +20,17 @@ public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connec
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);

// ObjectMapper에 JSR310 모듈 추가 및 타입 정보 포함 설정
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

// 타입 정보를 포함하여 직렬화 (LinkedHashMap 문제 해결)
objectMapper.activateDefaultTyping(
BasicPolymorphicTypeValidator.builder()
.allowIfBaseType(Object.class)
.build(),
ObjectMapper.DefaultTyping.NON_FINAL
);

// Key는 String으로, Value는 JSON으로 직렬화
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));
template.setHashKeySerializer(new StringRedisSerializer());
Expand All @@ -41,4 +39,9 @@ public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connec
template.afterPropertiesSet();
return template;
}

@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor)
.addPathPatterns("/order/**", "/api/order/**")
.addPathPatterns("/order/**", "/api/order/**", "/book/**", "/api/recent-books")
.excludePathPatterns("/login", "/register");
}
}
19 changes: 19 additions & 0 deletions src/main/java/com/fastcampus/book_bot/common/utils/JwtUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.Date;
Expand All @@ -16,6 +19,7 @@
@Component
@Data
@ConfigurationProperties(prefix = "jwt")
@Slf4j
public class JwtUtil {

private String secretKey;
Expand Down Expand Up @@ -107,4 +111,19 @@ public boolean validateToken(String token, Integer userId) {
return (tokenUserId.equals(userId) && !isTokenExpired(token));
}

public Integer extractUserIdFromRequest(HttpServletRequest request) {
String authorization = request.getHeader("Authorization");
if (authorization != null && authorization.startsWith("Bearer ")) {
try {
String accessToken = authorization.substring(7);
if (!isTokenExpired(accessToken)) {
return extractUserId(accessToken);
}
} catch (Exception e) {
log.debug("Authorization Header JWT 파싱 실패", e);
}
}
return null;
}

}
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
package com.fastcampus.book_bot.controller;

import com.fastcampus.book_bot.common.utils.JwtUtil;
import com.fastcampus.book_bot.domain.book.Book;
import com.fastcampus.book_bot.dto.keyword.KeywordDTO;
import com.fastcampus.book_bot.service.navigation.PopularKeywordService;
import com.fastcampus.book_bot.service.navigation.RecentlyViewService;
import com.fastcampus.book_bot.service.order.BestSellerService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Collections;
import java.util.List;

@Controller
Expand All @@ -16,9 +22,13 @@
public class MainController {

private final BestSellerService bestSellerService;
private final PopularKeywordService popularKeywordService;
private final RecentlyViewService recentlyViewService;
private final JwtUtil jwtUtil;

@GetMapping
public String main(Model model) {
public String main(HttpServletRequest request,
Model model) {
try {
// 월간 베스트셀러 데이터 조회 및 캐시 업데이트
bestSellerService.getMonthBestSeller();
Expand All @@ -28,20 +38,40 @@ public String main(Model model) {
bestSellerService.getWeekBestSeller();
List<Book> weeklyBestSellers = bestSellerService.getWeekBestSeller();

// 모델에 데이터 추가
List<KeywordDTO> popularKeywords = popularKeywordService.getPopularKeywords(5);

model.addAttribute("monthlyBestSellers", monthlyBestSellers);
model.addAttribute("weeklyBestSellers", weeklyBestSellers);
model.addAttribute("popularKeywords", popularKeywords);

log.info("BestSellers loaded - Monthly: {}, Weekly: {}",
monthlyBestSellers.size(), weeklyBestSellers.size());

} catch (Exception e) {
log.error("Error loading bestsellers", e);
// 에러 발생시 빈 리스트로 처리
model.addAttribute("monthlyBestSellers", List.of());
model.addAttribute("weeklyBestSellers", List.of());
}

return "index";
}

@GetMapping("/test/db")
public String mainWithDB(Model model) {
try {
List<Book> monthlyBestSellers = bestSellerService.getMonthBestSellerFromDB();
List<Book> weeklyBestSellers = bestSellerService.getWeekBestSellerFromDB();

model.addAttribute("monthlyBestSellers", monthlyBestSellers);
model.addAttribute("weeklyBestSellers", weeklyBestSellers);

log.info("DB BestSellers loaded - Monthly: {}, Weekly: {}",
monthlyBestSellers.size(), weeklyBestSellers.size());
} catch (Exception e) {
log.error("Error loading bestsellers from DB", e);
model.addAttribute("monthlyBestSellers", List.of());
model.addAttribute("weeklyBestSellers", List.of());
}
return "index";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.fastcampus.book_bot.controller.book;

import com.fastcampus.book_bot.domain.book.Book;
import com.fastcampus.book_bot.service.order.BestSellerService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequiredArgsConstructor
public class BestSellerApiController {

private final BestSellerService bestSellerService;

@GetMapping("/api/bestseller/redis")
public List<Book> getBestSellerRedis() {
return bestSellerService.getMonthBestSeller();
}

@GetMapping("/api/bestseller/db")
public List<Book> getBestSellerDB() {
return bestSellerService.getMonthBestSellerFromDB();
}
}
Original file line number Diff line number Diff line change
@@ -1,30 +1,41 @@
package com.fastcampus.book_bot.controller.book;

import com.fastcampus.book_bot.common.utils.JwtUtil;
import com.fastcampus.book_bot.domain.book.Book;
import com.fastcampus.book_bot.domain.user.User;
import com.fastcampus.book_bot.dto.book.SearchDTO;
import com.fastcampus.book_bot.service.book.BookSearchService;
import com.fastcampus.book_bot.service.navigation.PopularKeywordService;
import com.fastcampus.book_bot.service.navigation.RecentlyViewService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
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.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Controller
@RequiredArgsConstructor
@Slf4j
public class BookController {

private final BookSearchService bookSearchService;
private final PopularKeywordService popularKeywordService;
private final RecentlyViewService recentlyViewService;
private final JwtUtil jwtUtil;

public BookController(BookSearchService bookSearchService) {
this.bookSearchService = bookSearchService;
}

@GetMapping("/search")
public String searchBooks(@ModelAttribute SearchDTO searchDTO,
Expand All @@ -37,6 +48,8 @@ public String searchBooks(@ModelAttribute SearchDTO searchDTO,
pageable
);

popularKeywordService.recordKeyword(searchDTO);

searchDTO.setSearchResult(searchResult);
searchDTO.setPageInfo(pageable);

Expand All @@ -46,14 +59,45 @@ public String searchBooks(@ModelAttribute SearchDTO searchDTO,
}

@GetMapping("/book/{bookId}")
public String bookDetail(@PathVariable Integer bookId, Model model) {
public String bookDetail(@PathVariable Integer bookId,
HttpServletRequest request,
Model model) {

Optional<Book> book = bookSearchService.getBookById(bookId);
if (book.isPresent()) {
model.addAttribute("book", book.get());
return "book/detail";
} else {
if (book.isEmpty()) {
return "error/404";
}

model.addAttribute("book", book.get());

Integer userId = jwtUtil.extractUserIdFromRequest(request);
if (userId != null) {
try {
recentlyViewService.addRecentBook(userId, bookId);
log.info("최근 본 상품 추가 - UserId: {}, BookId: {}", userId, bookId);
} catch (Exception e) {
log.error("최근 본 상품 추가 실패 - UserId: {}, BookId: {}", userId, bookId, e);
}
}

return "book/detail";
}

@GetMapping("/api/recent-books")
@ResponseBody
public ResponseEntity<List<Book>> getRecentBooks(HttpServletRequest request) {
Integer userId = jwtUtil.extractUserIdFromRequest(request);

if (userId == null) {
return ResponseEntity.ok(Collections.emptyList());
}

try {
List<Book> recentBooks = recentlyViewService.getRecentBookIds(userId);
return ResponseEntity.ok(recentBooks);
} catch (Exception e) {
log.error("최근 본 상품 조회 실패 - UserId: {}", userId, e);
return ResponseEntity.ok(Collections.emptyList());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.fastcampus.book_bot.domain.navigation;

import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.time.LocalDateTime;

@Entity
@Table(name = "popular_keyword")
@EntityListeners(AuditingEntityListener.class)
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class PopularKeyword {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Integer id;

@Column(name = "KEYWORD", nullable = false, length = 100)
private String keyword;

@Column(name = "COUNT", nullable = false)
@Builder.Default
private Integer count = 0;

@CreatedDate
@Column(name = "CREATED_AT", updatable = false)
private LocalDateTime createdAt;

@LastModifiedDate
@Column(name = "UPDATED_AT")
private LocalDateTime updatedAt;
}
Loading