我使用 Spring Kafka 并撰寫了 Producer Class
@Component
@RequiredArgsConstructor
class Producer {
private static final String TOPIC = "channels";
private static final Logger LOGGER = Logger.getLogger(Producer.class.getName());
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@EventListener(ApplicationStartedEvent.class)
public void channels_01() throws IOException {
}
@EventListener(ApplicationStartedEvent.class)
public void channels_02()throws IOException {
}
@EventListener(ApplicationStartedEvent.class)
public void channels_03()throws IOException {
}
}
是否可以同時運行 3 個 @Eventlistener 注釋方法作為生產者?3 種方法將記錄發送到完全相同的主題。spring 容器和 kafka 服務器會將它們識別為 3 個獨立的生產者客戶端嗎?
uj5u.com熱心網友回復:
如果您想擁有三個生產者客戶端,那么您需要擁有三個KafkaTemplate并使用以下producerPerThread = true選項DefaultKafkaProducerFactory:
/**
* Set to true to create a producer per thread instead of singleton that is shared by
* all clients. Clients <b>must</b> call {@link #closeThreadBoundProducer()} to
* physically close the producer when it is no longer needed. These producers will not
* be closed by {@link #destroy()} or {@link #reset()}.
* @param producerPerThread true for a producer per thread.
* @since 2.3
* @see #closeThreadBoundProducer()
*/
public void setProducerPerThread(boolean producerPerThread) {
然后你需要確保它ApplicationEventMulticaster是異步的。見SimpleApplicationEventMulticaster:
/**
* Set a custom executor (typically a {@link org.springframework.core.task.TaskExecutor})
* to invoke each listener with.
* <p>Default is equivalent to {@link org.springframework.core.task.SyncTaskExecutor},
* executing all listeners synchronously in the calling thread.
* <p>Consider specifying an asynchronous task executor here to not block the
* caller until all listeners have been executed. However, note that asynchronous
* execution will not participate in the caller's thread context (class loader,
* transaction association) unless the TaskExecutor explicitly supports this.
* @see org.springframework.core.task.SyncTaskExecutor
* @see org.springframework.core.task.SimpleAsyncTaskExecutor
*/
public void setTaskExecutor(@Nullable Executor taskExecutor) {
為它注冊一個帶有名稱的 beanapplicationEventMulticaster并設定一個期望TaskExecutor以確保您的@EventListener方法被并行呼叫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/471015.html
