현재 시스템은 컨슈머가 이벤트를 처리할 때 에러가 발생하면, 쿠폰 발급 count는 증가하지만 실제 쿠폰은 발급되지 않는 문제가 있다.
@Component
public class CouponCreatedConsumer {
private final CouponRepository couponRepository;
public CouponCreatedConsumer(CouponRepository couponRepository) {
this.couponRepository = couponRepository;
}
@KafkaListener(topics = "coupon_create", groupId = "group_1")
public void listener(Long userId) {
couponRepository.save(new Coupon(userId));
}
}
@Entity
public class FailedEvent {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long userId;
public FailedEvent() {}
public FailedEvent(Long userId) {
this.userId = userId;
}
}
public interface FailedEventRepository extends JpaRepository<FailedEvent, Long> {
}
@Component
public class CouponCreatedConsumer {
private final CouponRepository couponRepository;
private final FailedEventRepository failedEventRepository;
private final Logger logger = LoggerFactory.getLogger(CouponCreatedConsumer.class);
public CouponCreatedConsumer(CouponRepository couponRepository, FailedEventRepository failedEventRepository) {
this.couponRepository = couponRepository;
this.failedEventRepository = failedEventRepository;
}
@KafkaListener(topics = "coupon_create", groupId = "group_1")
public void listener(Long userId) {
try {
couponRepository.save(new Coupon(userId));
} catch (Exception e) {
logger.error("failed to create coupon::"+userId);
failedEventRepository.save(new FailedEvent(userId));
}
}
}