@RequiredArgsConstructor
@Slf4j
@Service
public class FixedOrderProcessor {
private final JdbcTemplate jdbcTemplate;
private final RestTemplate restTemplate;
private final JavaMailSender mailSender;
private final PaymentProperties paymentProperties;
//нигде не используется
private static final int TIMEOUT = 30000;
 
private static final int FIELD_COUNT = 5;
@KafkaListener(topics = "${app.kafka.order.topic}",
groupId = "${app.kafka.order.group-id}",
containerFactory = "kafkaListenerContainerFactory")
public void processOrder(String message) {
try {
OrderMessage order = parse(message);
log.info("Processing order: userId={}, productId={}", order.userId(), order.productId());
String productSql = "SELECT price FROM products WHERE id = ?";
BigDecimal price = jdbcTemplate.queryForObject(productSql, BigDecimal.class, order.productId());
int updated = jdbcTemplate.update(
"UPDATE users SET balance = balance - ? WHERE id = ? AND balance>= ?",
price, order.userId(), price);
if (updated == 0) {
throw new IllegalStateException(Я вот скинул тебе тот порядок, который у меня есть, и это хуйня полная, получается. Или я до конца не понимаю просто, как это работает.
"Insufficient funds or user not found: userId=%s, price=%s"
.formatted(order.userId(), price));
}
String insertSql = "INSERT INTO orders (user_id, product_id, amount, comment) " +
"VALUES (?, ?, ?, ?)";
jdbcTemplate.update(insertSql, order.userId(), order.productId(), price, order.comment());
PaymentResponse payment = restTemplate.postForObject(
paymentProperties.url(),
new PaymentRequest(order.userId(), price, order.promoCode()),
PaymentResponse.class);
 
//вынести
try {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setTo(order.customerEmail());
mail.setSubject("Order confirmed");
mail.setText("Order for %s confirmed!".formatted(order.productId()));
mailSender.send(mail);
} catch (Exception e) {
System.out.println("Email error: " + e.getMessage());
}
log.info("Order processed: " + userId);
//
} catch (Exception e) {
//log.error("...")
System.err.println("Critical error in Kafka consumer: " + e.getMessage()); //убрал бы
}
}
private static OrderMessage parse(String message) {
String[] parts = message.split("\\|", -1);
if (parts.length != FIELD_COUNT) {
throw new MalformedOrderMessageException(
"Expected %d fields, got %d".formatted(FIELD_COUNT, parts.length));
}
return new OrderMessage(parts[0], parts[1], parts[2], parts[3], parts[4]);
}
 
 
@Validated
@ConfigurationProperties(prefix = "app.payment")
public record PaymentProperties(
@NotBlank String baseUrl,
@NotNull Duration timeout) {
}
 
application.properties
app:
kafka:
order:
topic: order-topic
group-id: order-processor-group
payment:
url: https://payment-gateway.com/charge
timeout: 30s
 
 
 
//что за тип var
List<String> list = List.of("a", "b", "c");
var x = list.stream().map(x -> x.toUpperCase());
 
Есть два метода:
boolean a();
boolean b();
 
// Всегда ли вызывается b() здесь ?
if (a() && b()) ...
 
// ... и здесь?
if (a() & b()) ...