-
Notifications
You must be signed in to change notification settings - Fork 0
9_Application Events and Listeners #8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| package org.javaspringcourse.config; | ||
|
|
||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.scheduling.annotation.EnableAsync; | ||
| import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; | ||
|
|
||
| @Configuration | ||
| @EnableAsync | ||
| public class AsyncConfig { | ||
|
|
||
| @Bean | ||
| ThreadPoolTaskExecutor threadPoolTaskExecutor() { | ||
| return new ThreadPoolTaskExecutor(); // TODO здесь можно определить ограничения для потоков асинхронных ивентов | ||
| }; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| package org.javaspringcourse.order.controller; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import org.javaspringcourse.order.dto.OrderIn; | ||
| import org.javaspringcourse.order.service.OrderService; | ||
| import org.springframework.web.bind.annotation.PostMapping; | ||
| import org.springframework.web.bind.annotation.RequestBody; | ||
| import org.springframework.web.bind.annotation.RequestMapping; | ||
| import org.springframework.web.bind.annotation.RestController; | ||
|
|
||
| @RestController | ||
| @RequestMapping("/orders") | ||
| @RequiredArgsConstructor | ||
| public class OrderController { | ||
| private final OrderService orderService; | ||
|
|
||
| @PostMapping("/create") | ||
| public void getOrders(@RequestBody OrderIn order) { | ||
| orderService.createOrder(order.cost(), order.balance()); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| package org.javaspringcourse.order.dto; | ||
|
|
||
| public record OrderIn(float cost, float balance) {} |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| package org.javaspringcourse.order.eventListener; | ||
|
|
||
| import lombok.extern.log4j.Log4j2; | ||
| import org.javaspringcourse.order.eventListener.event.OrderCreatedEvent; | ||
| import org.springframework.context.event.EventListener; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| @Log4j2 | ||
| @Component | ||
| public class OrderEventListener { | ||
|
|
||
| @EventListener | ||
| public void handleOrderCreatedEvent(OrderCreatedEvent event) { | ||
| log.info("Handle OrderCreatedEvent..."); | ||
| log.info("Order was created."); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| package org.javaspringcourse.order.eventListener; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.log4j.Log4j2; | ||
| import org.javaspringcourse.order.eventListener.event.OrderCreatedEvent; | ||
| import org.javaspringcourse.payment.eventListener.event.PaymentProcessedEvent; | ||
| import org.springframework.context.ApplicationEventPublisher; | ||
| import org.springframework.scheduling.annotation.Async; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.transaction.event.TransactionPhase; | ||
| import org.springframework.transaction.event.TransactionalEventListener; | ||
|
|
||
| @Log4j2 | ||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class PaymentProcessedEventListener { | ||
| private final ApplicationEventPublisher eventPublisher; | ||
|
|
||
| @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) | ||
| public void handlePaymentSuccessEvent(PaymentProcessedEvent event) { | ||
| log.info("Handle PaymentProcessedEvent (AFTER_COMMIT)..."); | ||
| log.info("Publish OrderCreatedEvent."); | ||
| eventPublisher.publishEvent(new OrderCreatedEvent()); | ||
| } | ||
|
|
||
| @TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK) | ||
| public void handlePaymentFailEvent(PaymentProcessedEvent event) { | ||
| log.info("Handle PaymentProcessedEvent (AFTER_ROLLBACK)..."); | ||
| log.info("Order has been cancelled."); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| package org.javaspringcourse.order.eventListener.event; | ||
|
|
||
| public record OrderCreatedEvent() { | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| package org.javaspringcourse.order.eventListener.event; | ||
|
|
||
| public record OrderCreatingEvent(float cost, float money) { | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| package org.javaspringcourse.order.service; | ||
|
|
||
| import jakarta.transaction.Transactional; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.log4j.Log4j2; | ||
| import org.javaspringcourse.order.eventListener.event.OrderCreatingEvent; | ||
| import org.springframework.context.ApplicationEventPublisher; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.support.TransactionSynchronizationManager; | ||
|
|
||
| @Log4j2 | ||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class OrderService { | ||
| private final ApplicationEventPublisher eventPublisher; | ||
|
|
||
| public void createOrder(float cost, float money) { | ||
| log.info("Creating an order..."); | ||
| log.info("Waiting for payment..."); | ||
|
|
||
| log.info("Publish OrderCreatingEvent."); | ||
| eventPublisher.publishEvent(new OrderCreatingEvent(cost, money)); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| package org.javaspringcourse.payment.eventListener; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.log4j.Log4j2; | ||
| import org.javaspringcourse.order.eventListener.event.OrderCreatingEvent; | ||
| import org.javaspringcourse.payment.service.PaymentService; | ||
| import org.springframework.context.event.EventListener; | ||
| import org.springframework.scheduling.annotation.Async; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| @Log4j2 | ||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class OrderCreatingEventListener { | ||
| private final PaymentService paymentService; | ||
|
|
||
| @EventListener | ||
| @Async("threadPoolTaskExecutor") | ||
| public void handleOrderCreatingEvent(OrderCreatingEvent event) throws InterruptedException { | ||
| Thread.sleep(2000); // имитация долгой работы | ||
| try { | ||
| paymentService.processPayment(event.money(), event.cost()); | ||
| } catch (Exception e) { | ||
| log.warn(e); | ||
| } | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| package org.javaspringcourse.payment.eventListener; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. пакеты в java лучше называть либо одним словом, либо без разделителей. eventlistener |
||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.log4j.Log4j2; | ||
| import org.javaspringcourse.payment.eventListener.event.PaymentProcessedEvent; | ||
| import org.springframework.scheduling.annotation.Async; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.transaction.event.TransactionPhase; | ||
| import org.springframework.transaction.event.TransactionalEventListener; | ||
|
|
||
| @Log4j2 | ||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class PaymentEventListener { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Точно такой же перехватчик находится в пакете org.javaspringcourse.order.eventListener. Зачем это нужно? |
||
|
|
||
| @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) | ||
| public void handlePaymentSuccessEvent(PaymentProcessedEvent event) { | ||
| log.info("Handle PaymentProcessedEvent (AFTER_COMMIT)..."); | ||
| log.info("Payment was successful."); | ||
| } | ||
|
|
||
| @TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK) | ||
| public void handlePaymentFailEvent(PaymentProcessedEvent event) { | ||
| log.info("Handle PaymentProcessedEvent (AFTER_ROLLBACK)..."); | ||
| log.info("Payment failed."); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| package org.javaspringcourse.payment.eventListener.event; | ||
|
|
||
| public record PaymentProcessedEvent() { | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| package org.javaspringcourse.payment.service; | ||
|
|
||
| import jakarta.transaction.Transactional; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.log4j.Log4j2; | ||
| import org.javaspringcourse.payment.eventListener.event.PaymentProcessedEvent; | ||
| import org.springframework.context.ApplicationEventPublisher; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.support.TransactionSynchronizationManager; | ||
|
|
||
| import static jakarta.transaction.Transactional.TxType.REQUIRES_NEW; | ||
|
|
||
| @Log4j2 | ||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class PaymentService { | ||
| private final ApplicationEventPublisher eventPublisher; | ||
|
|
||
| @Transactional(value = REQUIRES_NEW, rollbackOn = Exception.class) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Я пробовал запускать проект и транзакция здесь не открывается даже с этими параметрами. Попробуй пересмотреть логику |
||
| public void processPayment(float money, float need) { | ||
| log.info("Trying to pay for order. Current money: {}", money); | ||
| log.info("Publish PaymentProcessedEvent."); | ||
| eventPublisher.publishEvent(new PaymentProcessedEvent()); | ||
|
|
||
| log.info("In transaction: {}", TransactionSynchronizationManager.isActualTransactionActive()); | ||
|
|
||
| if (money > need) { | ||
| log.info("Payment Working..."); | ||
| log.info("Fixing in DB..."); | ||
| } else { | ||
| throw new RuntimeException("NO MONEY TO PAY"); | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,3 @@ | ||
| spring.application.name=java-spring-course | ||
| spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration | ||
| server.port=8080 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
не обязательно публиковать. Можно сделать return этого события. Спринг сам его опубликует