2 Kasım 2021 Salı

SpringKafka Producer TopicBuilder Sınıfı

Giriş
Şu satırı dahil ederiz
import org.springframework.kafka.config.TopicBuilder;
Örnek
Şöyle yaparız
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.kafka.config.TopicBuilder;

@Configuration
public class TopicProducer {

  static final String NAME_INCREMENT = "name_increment";
  static final String NAME_DECREMENT = "name_decrement";

  @Bean
  public NewTopic increment() {
    return TopicBuilder.name(NAME_INCREMENT)
      .partitions(10)
      .replicas(1)
      .build();
  }

  @Bean
  public NewTopic decrement() {
    return TopicBuilder.name(NAME_DECREMENT)
      .partitions(10)
      .replicas(1)
      .build();
  }
}
Kullanmak için şöyle yaparız
@Service
public class NameService {

  @Autowired
  private final KafkaTemplate<String, Name> template;

  public void decrement(String name) {
    template.send(TopicProducer.NAME_DECREMENT, new Name(name));
  }

  public void increment(String name) {
    template.send(TopicProducer.NAME_INCREMENT, new Name(name));
  }
}
Kullanmak için şöyle yaparız
@Component
public class NameConsumer {

  @KafkaListener(id = "increment", topics = TopicProducer.NAME_INCREMENT)
  public void increment(Name name) {
    ...
   }

  @KafkaListener(id = "decrement", topics = TopicProducer.NAME_DECREMENT)
  public void decrement(Name name) {
    ...
  }
}
 

 

Hiç yorum yok:

Yorum Gönder