멀티 모듈 구성
의존성
- Spring Web
- JPA
- mysql connector
요구사항
- 선착순 100명에게만 지급되어야 한다. 101개 이상이 지급되면 안된다.
- 순간적으로 몰리는 트래픽을 버틸 수 있어야 한다.
- 쿠폰 발급 외의 시스템에는 영향이 없어야 한다.
쿠폰 발급 로직
@Entity
public class Coupon {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long userId;
public Coupon() {
}
public Coupon(Long userId) {
this.userId = userId;
}
public Long getId() {
return id;
}
}
public interface CouponRepository extends JpaRepository<Coupon, Long> {
}
@Service
public class ApplyService {
private final CouponRepository couponRepository;
public ApplyService(CouponRepository couponRepository) {
this.couponRepository = couponRepository;
}
@Transactional
public void apply(Long userId) {
long count = couponRepository.count();
if (count > 100) {
return;
}
couponRepository.save(new Coupon(userId));
}
}
@SpringBootTest
class ApplyServiceTest {
@Autowired private ApplyService applyService;
@Autowired private CouponRepository couponRepository;
@Test
public void 한번만_응모() {
applyService.apply(1L);
long count = couponRepository.count();
assertThat(count).isEqualTo(1);
}
}