Monday, April 10, 2023

kafka-topics komutu - Topic yaratır, siler, listeler ve değiştirir.

Giriş 
Topic yaratır, siler, listeler ve değiştirir.

Docker İle Kullanım
Örnek
Şöyle yaparız. Burada "docker exe -t" ile çalıştırılacak kafka-topics belirtiliyor.
echo -e "\n-------- Creating Kafka Topics new_user --------"
docker exec -t kafka /usr/bin/kafka-topics \
--create --bootstrap-server :9092 \
      --topic new_user \
      --partitions 1 \
      --replication-factor 1
echo -e "\n-------- Creation Kafka Topics new_user Completed --------"
...

echo -e "\n-------- Creating Outbox Kafka Connector For Debezium --------"

curl -X POST  http://localhost:8083/connectors/ \
  -H 'content-type: application/json' \
  -d '{
   "name": "student-outbox-connector",
   "config": {
      "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
      "tasks.max": "1",
      "database.hostname": "postgres",
      "database.port": "5432",
      "database.user": "postgres",
      "database.password": "postgres",
      "database.dbname": "user_DB",
      "database.server.name": "pg-outbox-server",
      "tombstones.on.delete": "false",
      "table.whitelist": "public.outbox",
      "transforms": "outbox",
      "transforms.outbox.type": "com.eresh.outbox.OutboxTransformer"
   }
}'
--alter seçeneği
Örnek
Şöyle yaparız.
bin/kafka-topics.sh --zookeeper localhost:2181 --alter --topic topic1 
  config retention.ms=60000
bin/kafka-topics.sh --zookeeper localhost:2181 --alter --topic topic1
  —config file.delete.delay.ms=40000
bin/kafka-topics.sh --zookeeper localhost:2181 --alter --topic topic1
  --config segment.bytes=400000
--create seçeneği
Topic yaratır. Bu seçeneğin partition değeri ile ilgili Apache Kafka Partition Rakamını Hesaplama yazısına bakabilirsiniz

Örnek
Şöyle yaparız. 
--topic ile topic ismi belirtilir.
--partitions ile veri 10 tane partition 'a dağıtılıyor. 10 tane de consumer gerekir.
--bootstrap-server veya --zookeeper ile zookeeper adresi belirtilir. 
--bootstrap-server ile port numarası 9092'dir
--zookeeperile port numarası 2181'dir
kafka-topics.sh --create --bootstrap-server localhost:9092 --replication-factor 1
  --partitions 10 --topic topic-10p 
Örnek
Şöyle yaparız. Burada --zookeeper seçeneği kullanılıyor
kafka-topics.bat --create --zookeeper localhost:2181 --replication-factor 1 
  --partitions 1 --topic gpslocation
Örnek
Şöyle yaparız. Burada --zookeeper seçeneği port numarası vermeden kullanılıyor
$KAFKA_HOME/bin/kafka-topics.sh --zookeeper localhost --create --topic transrec
--partitions 1 --replication-factor 1
Örnek
Şöyle yaparız.  --config cleanup.policy=compact kullanılıyor. Compaction Of Topic Data yazısına bakabilirsiniz
$KAFKA_HOME/bin/kafka-topics.sh --zookeeper localhost --create --topic storage-topic
--partitions 1 --replication-factor 1
--config cleanup.policy=compact
Örnek
Şöyle yaparız. Burada Avro Schema Validation etkinleştiriliyor
/usr/bin/kafka-topics 
--create 
--bootstrap-server localhost:9092
--replication-factor 1 
--partitions 1 
--topic company
--config confluent.value.schema.validation=true

-- config seçeneği
Örnek
Açıklaması şöyle. Özellikle metin gönderirken sıkıştırma çok faydalı olabilir
Especially when using text-based formats such as JSON, the effects of compression can be quite pronounced, with compression ratios typically ranging from 5x to 7x.
Şöyle yaparız
bin/kafka-topics.sh 
  --create \
  --topic snappy-compressed-topic \
  --zookeeper localhost:2181 \
  --config compression.type=snappy 
  --replication-factor 1 \
  --partitions 1
--delete seçeneği
Topic siler
Örnek
Şöyle yaparız.
kafka-topics.sh --delete --topic topic-1p --bootstrap-server localhost:9092
Örnek
Şöyle yaparız
./bin/kafka-topics.sh \
  --delete \
  --topic my-topic
--describe seçeneği
--topic ile belirtilen topic için bilgi verir

Örnek
Şöyle yaparız
kafka-topics.bat --describe --zookeeper localhost:2181 --topic [Topic Name]
Örnek
Şöyle yaparız
./bin/kafka-topics.sh --zookeeper localhost:2181 --topic account_event --describe

Topic:account_event
PartitionCount:1        ReplicationFactor:1     Configs:
Topic: account_event    Partition: 0    Leader: 1       Replicas: 1     Isr: 1

--list seçeneği
Topicleri listeler
Örnek
Şöyle yaparız
kafka-topics --zookeeper zookeeper:2181 --list
Örnek
Şöyle yaparız.
bin/kafka-topics.sh --list --bootstrap-server localhost:9092
--replication-factor seçeneği
Şöyle yaparız.
bin/kafka-topics.sh --create --bootstrap-server localhost:9092 --replication-factor 1 
--partitions 1 --topic test
--zookeeper seçeneği - deprecated
--zookeeper deprecated. Bunun yerine --bootstrap-server kullanılmalı.

zookeper sunucusunun adresi belirtilir. Zookeeper varsayılan port olarak 2181'i kullanır. Tüm seçenekler için (alter, create, list vs) mutlaka zookeeper adresini belirtmek gerekir.
Örnek
Şöyle yaparız
kafka-topics.bat 
  --create 
  --zookeeper localhost:2181 
  --replication-factor 1 
  --partitions 1 
  --topic [topic name]

kafka-configs komutu - Modify The Topic Configuration

Giriş
alter seçeneğinden sonra --add-config veya --delete-config kullanılır

1.  --add-config seçeneği

Örnek - cleanup.policy Değiştirme
Şöyle yaparız. Burada cleanup.policy değeri değiştiriliyor
kafka-configs.sh 
  --zookeeper localhost:2181 
  --entity-type topics 
  --entity-name my_topic 
  --alter 
  --add-config cleanup.policy=compact
Örnek - min.insync.replicas
Şöyle yaparız
kafka-configs \
  --bootstrap-server localhost:9092 \
  --entity-type topics *
  --entity-name my-topic \
  --alter \
  --add-config min.insync.replicas=2
Örnek - retention.ms Değiştirme
Açıklaması şöyle
Use the kafka-configs command line tool to alter the retention policy for the topic to a very short period of time. Once the retention period has expired, the messages will be deleted automatically.
Şöyle yaparız. Burada retention.ms değeri değiştiriliyor
./bin/kafka-configs.sh \
  --alter \
  --entity-type topics \
  --entity-name my-topic \
  --add-config retention.ms=1000
2. --delete-config seçeneği

Örnek - min.insync.replicas
Şöyle yaparız
kafka-configs \
  --bootstrap-server localhost:9092 \
  --entity-type topics \
  --entity-name my-topic \
  --alter \
  --delete-config min.insync.replicas

Thursday, April 6, 2023

Kafka Producer KafkaProducer Sınıfı Batch Şeklinde Gönderir

Giriş
Açıklaması şöyle
Kafka producer sends messages in batches rather than one-by-one. Messages are first accumulated in RecordAccumulator, then a sender thread asynchronously sends the batched messages to Kafka broker. Batching is a major reason why Kafka can achieve high throughout in message processing.
RecordAccumulator Sınıfı
İki tane önemli bileşeni vardır
1. memory buffer pool
Açıklaması şöyle
Kafka does not directly rely on JVM for memory management, rather, it has BufferPool to optimize dynamic memory allocation and recycle.
2. a set of queues where messages are stored and batched before sending to brokers.

Çalışması şöyle. Yani her dequeue içinde ProducerBatch var. Periyodik yazma zamanı gelince ProducerBatch bir bütün olarak yazılır.
- messages assigned to the same TopicPartition are stored in the same Deque.
- Each Deque contains multiple ProducerBatches, each ProducerBatch contains multiple messages.
- Messages are sent to the broker at the ProducerBatch granularity.
- Buffer pool has default size of 32 MB, each pooled memory block has default size of 16 KB.

Kafka Producer KafkaProducer Sınıfı

Giriş
Şu satırı dahil ederiz
import org.apache.kafka.clients.producer.KafkaProducer;
Sınıf generic olduğu için K,V şeklinde tanımlanır
KafkaProducer<K, V> producer 
Bu sınıfın send() metodu asenkron çalışır. 

constructor - Properties
Sadece şu değerleri vermek yeterli.
"bootstrap.servers"
"key.serializer", 
"value.serializer",
Şeklen şöyle


Serializer olarak şunlar gibi sınıflar kullanılabilir
org.apache.kafka.common.serialization.IntegerSerializer
org.apache.kafka.common.serialization.StringSerializer;

Örnek
Şöyle yaparız
Properties props = new Properties();
//Assign localhost id
props.put("bootstrap.servers", "localhost:9092");

//If the request fails, the producer can automatically retry,
props.put("retries", 0);
props.put("batch.size", 250000);
props.put("linger.ms", 5000);
props.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer","org.apache.kafka.common.serialization.ByteArraySerializer");
Producer<String, byte[]> producer = new KafkaProducer<>(props);
Örnek
Şöyle yaparız.
String TOPIC_NAME = "test";
String object ="hello";

Properties props=new Properties();
props.put("bootstrap-server", "localhost:9092");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
ProducerConfig config = new ProducerConfig(props);

KafkaProducer<String,String> sampleProducer= new KafkaProducer<String,String>(props);
initTransactions(), beginTransaction(), commitTransaction(), abortTransaction() metodları

flush metodu
Örnek
Şöyle yaparız
KafkaProducer<String, String> kafkaProducer = ...
ProducerRecord<String, String> record = ...

kafkaProducer.send(record);

kafkaProducer.flush();
kafkaProducer.close();
send metodu - ProducerRecord
send metodu yazısına taşıdım

send metodu - ProducerRecord + Callback
send metodu ve Callback yazısına taşıdım













Kafka Streams KStream Arayüzü - Unbound Stream of Events

Giriş
Şu satırı dahil ederiz
import org.apache.kafka.streams.kstream.KStream;
Açıklaması şöyle
Kafka Streams provides two main abstractions for processing data: KStream and KTable. 
- A KStream represents an unbounded stream of records that can be transformed with stateless operations such as mapping, filtering, joining, and aggregating. 
- A KTable represents a changelog stream of records that can be queried by key and updated with stateful operations such as counting, grouping, windowing, and joining.
constructor
Örnek  - KStreamBuilder - Kullanmayın
KStreamBuilder  artık deprecated. Şöyle yaparız
KStreamBuilder builder = new KStreamBuilder();
//KStream for topic
KStream<String, String> textLines = builder.stream("TextLinesTopic");
Örnek
StreamBuilder tarafından yaratılır.. Şöyle yaparız
StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> textLines = builder.stream("streams-plaintext-input");

aggregate metodu
KStream.aggregate metodu yazısına taşıdım

count metodu
KStreams.count metodu yazısına taşıdım

filter metodu
KStream.filter metodu yazısına taşıdım

filterNot metodu
KStream.filterNot metodu yazısına taşıdım

flatmapValues metodu
KStream.flatmapValues metodu yazısına taşıdım

groupBy metodu
KStream.groupBy metodu yazısına taşıdım

groupByKey metodu
KStream.groupByKey metodu yazısına taşıdım

map metodu
KStream.map metodu yazısına taşıdım

mapValues metodu
KStream.mapValues metodu yazısına taşıdım

to metodu
KStream.to metodu yazısına taşıdım

windowedBy metodu
KStream.windowedBy metodu yazısına taşıdım






















Tuesday, April 4, 2023

Kafka Connect DatagenConnector Sınıfı - Test İçindir

Giriş
Bu connector test amaçlı rastgele veri üretir. quickstart şemasında hazır (Quick Start Predefined Schemas) nesneler var. 

Hazır nesne listesi burada

Açıklaması şöyle
Parameter Description                                         Default
max.interval Max interval between messages (ms)                         500
iterations Number of messages to send from each task, or less than 1 for unlimited -1

Örnek
Java ile yazılmış bir test kodu burada

Örnek - Orders
Hazır gelen nesnelerden bir tanesi Orders. Bu nesneleri orders_json isimli kuyruğa JSON olarak göndermek için şöyle yaparız. Toplam 1000 tane nesne üretir
{
  "name": "datagen-orders",
  "config": {
    "connector.class": "io.confluent.kafka.connect.datagen.DatagenConnector",
    "kafka.topic": "orders_json",
    "quickstart": "orders",
    "key.converter": "org.apache.kafka.connect.storage.StringConverter",
    "value.converter": "org.apache.kafka.connect.json.JsonConverter",
    "value.converter.schemas.enable": "false",
    "max.interval": 1000,
    "iterations": 1000,
    "tasks.max": "1"
  }
}

Kafka Connect SourceRecord Sınıfı

Giriş
Şu satırı dahil ederiz
import org.apache.kafka.connect.source.SourceRecord;
SourceTask nesnesinin poll() çağrısı bize bu nesnenin listesini döndürür

SourceRecord kalıtımı şöyle
public class SourceRecord extends ConnectRecord<SourceRecord>
sourcePartition metodu
Örnek
Şöyle yaparız
Map<Map<String, ?>, Map<String, ?>> partitionsToOffset = new ConcurrentHashMap<>();

SourceRecord rec = ...;
partitionsToOffset.put(rec.sourcePartition(), rec.sourceOffset());
value metodu
Örnek
Şöyle yaparız
import org.apache.kafka.connect.data.Values;
import org.apache.kafka.connect.source.SourceRecord;

String convertToString(SourceRecord rec) {
  return Values.convertToString(rec.valueSchema(), rec.value());
}





Consumer Failover Across Data Centers

Active-Passive Consumption Across Data Centers Açıklaması şöyle In Kafka, a common consumption pattern for multi-data center setups in...