inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

173만명의 커뮤니티!! 함께 토론해봐요.

@RestController가 아닌 @Controller 사용에 대하여

미해결

스프링 시큐리티 완전 정복 [6.x 개정판]

@Controller의 url들을 통해 원하는 화면들을 전환하는 방식으로 일을 진행 중 입니다. Security를 적용하려 보니 강의에는 @RestController뿐인데 @RestController는 페이지 전환에 적합하지 않다고 알고 있습니다. 그렇다면 @Controller에 Security를 적용할 수 없는겁니까? 그리고 java version 17을 사용하셨는데 '왜 17을 사용하셨는지'와 '최신 버전인 22를 사용하면 어떠한 문제가 발생하는지'궁금합니다.

  • spring
  • spring-boot
  • spring-security
  • security
  • web-security
김지훈 댓글 1 좋아요 0 조회수 202

영상이 검정색으로 화면이 안보여요...

미해결

자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]

영상 실행은 되는데 화면이 검정색으로 뜨고 아무것도 안보여용...어제만 해도 별문제 없엇는데 확장프로그램 문제인가 해서 사파리로도 들어갔는데 똑같이 어둡게 나오네요... 혹시 다른 강의도 그런가 하고 다른분 강의 켜봤는데 그분 강의는 잘 화면이 나오고 여기 해당 강의만 어둡게나와요! 근데 아이패드로 접속해서 틀면 제대로 나오는데.. 노트북에서 보고 싶은데 해결방법이 뭘까요... 추가적으로 강력새로고침해서 캐시도 지워보고 시크릿모드에서도 해보고 다해봤는데도 같은 현상입니다. 혹시해서 확장프로그램 삭제하고 노트북도 껏다 켜봤습니닥 ㅠㅠ...

  • java
  • spring
  • aws
  • mysql
  • spring-boot
  • jpa
공존 댓글 4 좋아요 0 조회수 6441

스프링부트에서 게시글 등록(mp4 파일 포함)시 영상 바로 안보입니다.

미해결

현재 스프링부트에서 게시글을 등록하는 기능을 만들고 detail 페이지에서 등록한 내용을 확인할 수 있도록 설정했습니다. 게시글 제목, 내용, mp4 영상을 받도록 하고 있는데 게시글 등록 후 바로 detail 페이지에 들어가 확인하면 동영상이 보이지 않습니다. 그래서 경로가 잘못됐나 싶어서 페이지 소스 보기를 통해 확인해봤는데 경로도 정확하게 호출되고 있습니다. 그 후 서버 재실행 후 다시 확인해보니 그제서야 동영상이 보이고 있습니다. 이에 대한 해결 방법을 잘 모르겠습니다. 아래는 게시글 등록에 대한 컨트롤러 코드, 서비스 코드, html 코드입니다.

  • spring
  • spring-boot
  • java
댓글 1 좋아요 0 조회수 321

@Data 사용

미해결

스프링 시큐리티 완전 정복 [6.x 개정판]

AccountDto, AccountContext 에서 @Data를 사용하고 있는데 @Data 안에는 setter가 들어가있어 사용을 지양해야한다고 알고 있습니다. 혹시 강사님께서는 예제라서 사용하신건지 아니면 @Data를 여기서 사용해도 문제가 없는건지 궁금합니다.

  • spring
  • spring-boot
  • spring-security
  • security
  • web-security
김동준 댓글 1 좋아요 0 조회수 246

7장 스캐너 문제풀이3

미해결

김영한의 자바 입문 - 코드로 시작하는 자바 첫걸음

[질문 템플릿] 1. 강의 내용과 관련된 질문인가요? (예/아니오) 2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오) 3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오) [질문 내용] 여기에 질문 내용을 남겨주세요. input.nextLine(); 이거말고 처음에 Scanner scanner = new Scanner( System.in ) 이걸 우연히 while 안에 넣어서 해도 되는걸 확인했는데 이런 방법은 좋은 방법이 아닌가요?

  • java
  • 객체지향
김상준 댓글 1 좋아요 0 조회수 335

cropper 오류 문제로 질문드립니다..

미해결

스프링과 JPA 기반 웹 애플리케이션 개발

좋은 강의 덕분에 공부를 열심히 잘 하고 있습니다 선생님 감사드립니다. 다름이아니라 이번 강의 중 cropper 사용에서 똑같이 설치 후 이미지 파일을 불러오면 Uncaught TypeError: $newImage.cropper is not a function at reader.onload 지정된 함수가 아니라고 뜨는데 cropper가 안 먹혀서 그런 걸까요 ㅠㅠ..? 서치하고 코드를 계속 봐도 답이 나오지 않아 이렇게 질문 드립니다..

  • java
  • spring
  • spring-boot
  • jpa
  • thymeleaf
leekyungbin55 댓글 2 좋아요 0 조회수 308

AuthenticationManager에 초기화에 대해 질문있습니다

미해결

스프링 시큐리티 완전 정복 [6.x 개정판]

@Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception { return configuration.getAuthenticationManager(); } 위 처럼 Bean 으로 등록하게되면 내부 메서드에서 Bean으로 등록된 Builder를 통해 등록하는거 까지는 이해했는데요. 근데 여기서 setShareObject와 같은게 없는데 return http.build(); 빌드하게되면 HttpSecurity 메서드의 @Override protected void beforeConfigure() throws Exception { if (this.authenticationManager != null) { setSharedObject(AuthenticationManager.class, this.authenticationManager); } else { ObservationRegistry registry = getObservationRegistry(); AuthenticationManager manager = getAuthenticationRegistry().build(); if (!registry.isNoop() && manager != null) { setSharedObject(AuthenticationManager.class, new ObservationAuthenticationManager(registry, manager)); } else { setSharedObject(AuthenticationManager.class, manager); } } } 가 호출되어 여기서 else 조건을 타 getSharedObject 로 AuthenticationManagerBuilder 빌더 클래스를 다시 꺼내와서 빌드를 하는데 이렇게 되면 http.build 과정의 인증관리자와 스프링컨테이너에 있는 인증관리자는 서로 다른건가요? 같다면 우리가 등록한 Bean이 build 과정에서 나올것같은데 못찾겠습니다 ㅠㅠ..

  • spring
  • spring-boot
  • spring-security
  • security
  • web-security
smathj 댓글 2 좋아요 0 조회수 389

SecurityContextHolderStrategy 설명해주신 부분에서 기존 방식 변경 방식에 대한 질문입니다.

해결됨

스프링 시큐리티 완전 정복 [6.x 개정판]

안녕하세요, 24:00 에 말씀해주시는 SecurityContextHolderStrategy 사용하기부분에 기본방식과 변경방식 설명해주시는 부분에서 이해가 안되는 부분이 생겨 질문드립니다. 기존방식과 변경방식의 구현된 소스코드를 보니 내부에서(SecurityContextHolder.crateEmptyContext() 내부) 도 결론적으로는 strategy.createEmptyContext() 를 delegate 하는 방식으로 호출 되는것을 보았습니다. 6.x, 5.x, 4.x 모두 동일한듯합니다. /** * Allows retrieval of the context strategy. See SEC-1188. * @return the configured strategy for storing the security context. */ public static SecurityContextHolderStrategy getContextHolderStrategy() { return strategy; } /** * Delegates the creation of a new, empty context to the configured strategy. */ public static SecurityContext createEmptyContext() { return strategy.createEmptyContext(); } AbstractAuthenticationProcessingFilter 쪽에서 successfulAuthentication 쪽에 로직dl 6.x, 5.7 이하 버전 대가 다른단것은 확인했는데 /** * Puts the <code>Authentication</code> instance returned by the authentication * manager into the secure context. */ protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException { this.logger.debug(LogMessage.format("Authentication success: %s", authResult)); SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); context.setAuthentication(authResult); this.securityContextHolderStrategy.setContext(context); this.securityContextRepository.saveContext(context, request, response); if (this.eventPublisher != null) { this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass())); } if (this.authenticationSuccessHandler != null) { this.authenticationSuccessHandler.onAuthenticationSuccess(request, response, authResult); } } /** * Puts the <code>Authentication</code> instance returned by the authentication * manager into the secure context. */ protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException { if (logger.isDebugEnabled()) { logger.debug("Authentication success: " + authResult); } SecurityContextHolder.getContext().setAuthentication(authResult); // Fire event if (this.eventPublisher != null) { eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent( authResult, this.getClass())); } if (authenticationSuccessHandler != null) { authenticationSuccessHandler.onAuthenticationSuccess(request, response, authResult); } } 추측건데 strategy 쪽을 세팅할수있는 부분이 추가됨에따라 달라진 부분이라 생각이 되어 이부분도 말씀하신 의도와는 다를듯하여 /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } 경쟁조건 때문이라고 설명하신 부분에서 말씀하시는 의도를 다시 한번 알수있을까요.

  • spring
  • spring-boot
  • spring-security
  • security
  • web-security
램쥐뱅 댓글 2 좋아요 0 조회수 556

MVC와 API의 차이점

미해결

자바와 스프링 부트로 생애 최초 서버 만들기, 누구나 쉽게 개발부터 배포까지! [서버 개발 올인원 패키지]

안녕하세요 강사님!! 다름이 아니라 공부를 하다가 MVC와 API의 차이점(?)에 대해 알아보게 되었습니다! 그래서 내린 결론이 Spring MVC구조의 @Controller는 컨트롤러의 리턴값이 ViewResolver에 의해 해석되어서 특정 View가 html응답으로 전송된다. 반면 REST API구조의 @RestController에 의한 호출은 View를 리턴하는 것이 목적이 아닌, 데이터를 전송하는 것을 목적으로 응답이 전송되어 진다. 라고 내렸습니다. 첫번째로, 위에서 제가 내린 결론이 맞는 말인지와 두번째로, 그럼 MVC를 쓰는 경우와 API를 쓰는 경우가 언제인지가 궁금합니다. 제가 아직 개념이 부족해서 그런건지는 몰라도 MVC를 쓰면 프론트엔드의 역할이 없어지는게(?) 아닌가 하는 착각이 들어서... 답변 부탁드리겠습니다!!

  • java
  • spring
  • aws
  • mysql
  • spring-boot
  • jpa
JMJ 댓글 1 좋아요 0 조회수 1156

JPAQueryFactory(em)의 객체 생성자 오류에 대해서 질문이 있습니다ㅜㅜ

미해결

호돌맨의 요절복통 개발쇼 (SpringBoot, Vue.JS, AWS)

자꾸 이 오류가 뜹니다.. 제가 gradle로 하기엔 지금 프로젝트를 하고 있는게 maven이라 메이븐으로 따라가고 있는데 자꾸 생성자를 못찾는다고 뜨네요...ㅠㅠ 왜이러는지 모르겠어요.. 뭔가 설정이나 그런걸 잘못한건가요?

  • vue.js
  • aws
  • spring-boot
  • jpa
  • spring-security
이승환 댓글 2 좋아요 0 조회수 725

코드 확인 부탁드립니다 ㅠ

미해결

자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비

import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[][] arr = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { arr[i][j] = sc.nextInt(); } } int m = sc.nextInt(); int[] moves = new int[m]; for(int i = 0; i < m; i++){ moves[i] = sc.nextInt(); } ArrayList<Stack<Integer>> board = new ArrayList<>(); for(int i = 0; i < n; i++) { Stack<Integer> temp = new Stack<>(); for(int j = 0; j < n; j++) { if(arr[n-1-j][i] == 0) break; temp.push(arr[n-1-j][i]); } board.add(temp); } Stack<Integer> basket = new Stack<>(); int result = 0; for(int i = 0; i < m; i++) { int num = moves[i]-1; Stack<Integer> stack = board.get(num); if(stack.empty()) continue; int popNum = stack.pop(); if(!basket.isEmpty() && basket.peek() == popNum) { basket.pop(); result += 2; } else { basket.push(popNum); } } System.out.print(result); } } 어느 부분에서 틀린지 모르겠습니다. 확인 해주시면 감사하겠습니다.ㅠㅠ

  • java
  • 코딩-테스트
모깅 댓글 2 좋아요 0 조회수 220

Rest 예외 처리 - RestAuthenticationEntryPoint / RestAccessDeniedHandler 스프링빈 등록 질문

해결됨

스프링 시큐리티 완전 정복 [6.x 개정판]

안녕하세요 선생님 Rest 예외처리 편에서 선생님께서는 RestAuthenticationEntryPoint 와 RestAccessDeniedHandler을 따로 스프링 빈으로 등록하지 않고 객체를 생성하는식으로 하셨는데 제가 따로 스프링빈으로 등록하고 해도 잘 동작하던대 따로 빈으로 등록하지 않고 하신 이유가있을까요? 해당 코드는 제가 빈으로 따로 등록하고 테스트 했던 코드입니다.

  • spring
  • spring-boot
  • spring-security
  • security
  • web-security
배성환 댓글 2 좋아요 0 조회수 374

Access Token과 Refresh Token을 어디에 저장해야 할까요?

미해결

현재 프로젝트를 진행중인데, Access Token과 Refresh Token을 헤더에 담아 로컬스토리지에 저장하는 방법을 사용중입니다. 그런데 로컬 스토리지는 보안에 취약하다는 글을 보았습니다. 로컬 스토리지에 담아도 jwt 정책으로 대응이 가능하다는 글도 있었습니다. Access Token과 Refresh Token을 어디에 저장해야 할까요? 만약 로컬 스토리지나 쿠키에 저장한다면 어떻게 관리해야하나요?

  • java
  • spring
  • accesstoken
  • refreshtoken
  • localStorage
  • cookies
유하정 댓글 1 좋아요 0 조회수 2175

섹션 6. 순수 jbdc

해결됨

스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

이 부분이 임포트가 아예 안 됩니다ㅠㅠ import org.springframework.jdbc.datasource.DataSourceUtils; 그래서 DataSourceUtils .getConnection(dataSource); 이렇게 인텔리제이에서 빨간 불이 들어오구요ㅠㅠ DataSourceUtils에만 빨간 불이 들어옵니다!! 어떻게 해결해야 할까요!! private Connection getConnection() { return DataSourceUtils.getConnection(dataSource); } private void close(Connection conn, PreparedStatement pstmt, ResultSet rs) { try { if (rs != null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) { close(conn); } } catch (SQLException e) { e.printStackTrace(); } } private void close(Connection conn) throws SQLException { DataSourceUtils.releaseConnection(conn, dataSource); }

  • java
  • spring
  • mvc
  • spring-boot
권정익 댓글 1 좋아요 0 조회수 205

프로젝션 'new 명령어로 조회' 질문 입니다.

해결됨

자바 ORM 표준 JPA 프로그래밍 - 기본편

학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요. 1. 강의 내용과 관련된 질문을 남겨주세요. 2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요. (자주 하는 질문 링크: https://bit.ly/3fX6ygx) 3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요. (질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG) 질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요. ========================================= [질문 템플릿] 1. 강의 내용과 관련된 질문인가요? (예/아니오) 2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오) 3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오) [질문 내용] 여기에 질문 내용을 남겨주세요. 안녕하세요? 프로젝션 쿼리에 new 명령어 관련 헷갈리는 부분이 있어서 질문 드립니다! try{ Member member = new Member(); member.setUsername("member1"); member.setAge(10); em.persist(member); em.flush(); em.clear(); List<MemberDTO> result = em.createQuery("SELECT new jpql.MemberDTO(m.username, m.age) FROM Member m", MemberDTO.class) .getResultList(); MemberDTO memberDTO = result.get(0); System.out.println("memberDTO = " + memberDTO.getAge()); System.out.println("memberDTO = " + memberDTO.getUsername()); tx.commit(); } 위와 같은 쿼리를 실행하게 되면 상위에서 생성한 member 객체에 있는 값을 result 로 복사하고 result 값을 memberDTO List의 인덱스 0으로 들어 간 값을 조회하라는 뜻이 맞는건가요..? 수업듣다가 제가 이해한게 맞는지 헷갈려서 질문 드립니다.. 답변 부탁드립니다!! 감사합니다.

  • java
  • jpa
자바만판다 댓글 1 좋아요 0 조회수 342

SpinLock & Busy Waiting 강의 질문입니다.

미해결

자바 동시성 프로그래밍 [리액티브 프로그래밍 Part.1]

안녕하세요! 강의 너무 잘 듣고 있는 수강생입니다. 이전 동기화와 CPU의 관계 강의에서는 CPU가 두 개 이상의 명령어를 처리하면 원자성이 보장이 안된다고 설명을 하셨는데, SpinLock & Busy Waiting 강의에서 test_and_set(int *lock) 메서드는 CPU 하드웨어 계층에서 원자성이 보장된다는 게 이해가 잘 가지를 않습니다. test_and_set(int *lock) 이 메서드는 하나의 명령어만 처리하는 건가요??

  • java
  • 동시성
  • multithread
  • synchronisation
bom 댓글 1 좋아요 1 조회수 267

예외처리에 관해 이해가 어려운 부분이 있습니다.

미해결

스프링 시큐리티 완전 정복 [6.x 개정판]

안녕하세요 강의 잘 보고 있습니다. 다름이 아니라 예외를 처리하는 부분에서 이해가 잘 가지 않는 부분이 이렇게 질문을 드립니다. 스프링 시큐리티의 FilterChainProxy의 끝단에 예외를 처리하는 ExceptionTranslationFilter가 존재합니다. 해당 필터가 인가 예외를 처리하는 것까지는 이해하였습니다. 그러나 인증예외를 다루는 것이 조금 이해가 가지 않습니다. 스프링 시큐리티에서 제공하는 formLogin 인증을 포함한 모든 인증 방식은 ExceptionTranslationFilter앞에 존재합니다. 그럼에도 불구하고 인증 필터들에서 발생하는 예외들을 ExceptionTranslationFilter에서 처리를 합니다. 기존의 저는 예외가 발생할 즉시 바로 자신을 호출한 객체에게 예외를 반환하며 프로세스가 진행한다 알고 있는데 이는 스프링 시큐리티에서 인증예외를 처리하는 흐름과는 정 반대의 흐름입니다. 혹시 인증 필터에서 해당 예외가 발생할시 예외를 Throw하는 것이 아닌 다른방식으로 예외를 감싸서 ExceptionTranslationFilter까지 흘러가는 건가요? 아니면 제가 놓치는 부분이 있는걸까요?

  • spring
  • spring-boot
  • spring-security
  • security
  • web-security
이상민 댓글 2 좋아요 0 조회수 443

트랜젝션 옵션의 전파에 대해 질문드립니다.

미해결

실전! 스프링 데이터 JPA

예전에 영한님이 답변하신 내용 중에 스프링이 제공하는 트랜잭션은 처음 시작한 트랜잭션을 기반으로 전파됩니다. 그러니까 서비스에서 트랜잭션을 시작하면 리포지토리의 트랜잭션이 해당 트랜잭션을 그대로 이어 받습니다. 라는 내용이 있었습니다. 그렇다면, 컨트롤러, 서비스, 리포지토리 순으로 코드가 진행된다고 할 때, 만약 서비스 계층에 @Trasnactional(readonly=false) 가 걸려있고 리포지토리 계층에 @Trasnactional(readonly=true) 가 걸려있으면 서비스 계층이 먼저 호출되므로 readonly=false 옵션이 적용된 채로 리포지토리 계층까지(기존 리포지토리 계층의 옵션은 무시된채로) 코드가 흘러가는걸까요?

  • java
  • spring
  • spring-boot
  • jpa
Jaesang Yoon 댓글 2 좋아요 0 조회수 239

섹션.8 메서드 기반 권한 부여 @PreAuthorize

미해결

스프링 시큐리티 완전 정복 [6.x 개정판]

안녕하세요? 섹션8. 메서드 기반 권한 부여 강의 보다가 잘 안되는 부분이 있어서 질문 드립니다! (16분 쯤에 설명 나오는 부분입니다!) @GetMapping("/user/{id}") @PreAuthorize("#id == authentication.name") public String authentication(@PathVariable(name = "id") String id){ return id; } 해당 강의에서 user 로 로그인 시 위 url 로 접근이 가능했는데, 똑같이 해봤는데 403 이 떴습니다. 혹시나 해서 공유해주신 github 프로젝트로 해당 branch 로 체크아웃했더니 같은 현상이 나타납니다. 이것저것 시도해보다가 스프링 공식페이지에서 @P 어노테이션에 대한 설명이 있길래 아래와 같이 도입해봤더니 정상동작합니다. @GetMapping("/user/{id}") @PreAuthorize("#id == authentication.name") public String authentication(@P("id") @PathVariable(name = "id") String id){ return id; } https://docs.spring.io/spring-security/reference/servlet/authorization/method-security.html 강의 하실 때보다 시큐리티 버젼이 또 올라가서 안되는 부분이 생긴 것일까요? 아니면 제가 어떤 부분을 놓치고 있는걸까요? ㅠ

  • spring
  • spring-boot
  • spring-security
  • security
  • web-security
  • @preauthorize
Peter Choi 댓글 3 좋아요 0 조회수 609

consumer 셋팅 숫자 출력이 안됩니다.

미해결

실습으로 배우는 선착순 이벤트 시스템

docker exec -it kafka kafka-console-consumer.sh --topic coupon_create --bootstrap-server localhost:9092 --key-deserializer "org.apache.kafka.common.serialization.StringDeserializer" --value-deserializer "org.apache.kafka.common.serialization.LongDeserializer" 라고 터미너에 입력한 후에 테스트 코드 package com.example.coupon_server.service; import com.example.coupon_server.repository.CouponRepository; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; @SpringBootTest public class ApplyServiceTest { @Autowired private ApplyService applyService; @Autowired private CouponRepository couponRepository; @Test @DisplayName("쿠폰 한개 적용 테스트") public void applyOneCoupon() { applyService.applyCoupon(1L); long count = couponRepository.count(); assertThat(count).isEqualTo(1); } @Test @DisplayName("쿠폰 여러개 적용 테스트") public void applyMultiCoupon() throws InterruptedException { int threadCount = 1000; ExecutorService executorService = Executors.newFixedThreadPool(32); CountDownLatch latch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { long userId = i; executorService.submit(() -> { try { applyService.applyCoupon(userId); } finally { latch.countDown(); } }); } latch.await(); Thread.sleep(10000); long count = couponRepository.count(); assertThat(count).isEqualTo(100); } @Test @DisplayName("한명당 한개의 쿠폰만 발급") public void applyOneCouponPerUser() throws InterruptedException { int threadCount = 1000; ExecutorService executorService = Executors.newFixedThreadPool(32); CountDownLatch latch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { long userId = i; executorService.submit(() -> { try { applyService.applyCoupon(1L); } finally { latch.countDown(); } }); } latch.await(); Thread.sleep(10000); long count = couponRepository.count(); assertThat(count).isEqualTo(1); } } 로 작성했지만 터미널에서 강사님과 같이 숫자들이 찍히자 않습니다. 그리고 터미널 안의 글씨 너무 작은것 같아요

  • java
  • docker
  • spring-boot
  • kafka
  • redis
SJ 댓글 3 좋아요 0 조회수 476

인기 태그

인프런 TOP Writers

주간 인기글