配置:
spring.kafka.bootstrap-servers=192.168.0.107:9092
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.retries=1
spring.kafka.producer.acks=1
spring.kafka.producer.batch-size=65535
spring.kafka.producer.properties.linger.ms=0
spring.kafka.producer.buffer-memory=33554432
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.enable-auto-commit=true
spring.kafka.consumer.auto-commit-interval=1000ms
spring.kafka.consumer.auto-offset-reset=latest
spring.kafka.consumer.properties.session.timeout.ms=120000
spring.kafka.consumer.properties.request.timeout.ms=180000
spring.kafka.listener.missing-topics-fatal=false
生产者:
package com.gaarachen.kafka.service;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
@Component
public class MyProducer {
private KafkaTemplate<String, String> kafkaTemplate;
private ObjectMapper objectMapper;
@Autowired
public MyProducer(KafkaTemplate<String, String> kafkaTemplate, ObjectMapper objectMapper) {
this.kafkaTemplate = kafkaTemplate;
this.objectMapper = objectMapper;
}
public void sendEvent(JSONObject event) throws JsonProcessingException {
String json = objectMapper.writeValueAsString(event);
kafkaTemplate.send("my-topic", json);
}
}
消费者
package com.gaarachen.kafka.service;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class MyConsumer {
private Logger log = LoggerFactory.getLogger(MyConsumer.class);
private ObjectMapper objectMapper;
@Autowired
public MyConsumer(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@KafkaListener(topics = "my-topic", groupId = "my-group")
public void onMessage(ConsumerRecord<String, String> record) throws IOException {
String json = record.value();
JSONObject event = objectMapper.readValue(json, JSONObject.class);
// Process the event...
log.info("event={}", event.toJSONString());
}
}