Seamless integration with Kafka after Springboot1.5.2
Add dependencies
Compile ("Org.springframework.kafka:spring-kafka:1.1.2.release")
Add Application.properties
#kafka
# Specifies Kafka proxy address, can be multiple
spring.kafka.bootstrap-servers= 192.168.59.130:9092,192.168.59.131:9092,192.168.59.132:9092
# Specify default consumer group ID
Spring.kafka.consumer.group-id=mygroup
# Specifies the default topic ID
spring.kafka.template.default-topic= My-replicated-topic
# Specifies the number of threads in the listener container to increase the concurrency
spring.kafka.listener.concurrency= 3
# The number of messages sent per batch
spring.kafka.producer.batch-size= 1000
Configuration Enable Kafka
Package cn.xiaojf.today.data.kafka.configuration;
Import org.springframework.context.annotation.Configuration;
Import Org.springframework.kafka.annotation.EnableKafka;
/**
* Kafka configuration
* @author xiaojf 2017/3/24 14:09
/
@Configuration
@EnableKafka Public
class kafkaconfiguration {
}
Message producer
Package cn.xiaojf.today.data.kafka.producer;
Import Org.apache.kafka.clients.producer.Producer;
Import Org.apache.kafka.clients.producer.RecordMetadata;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.kafka.core.KafkaOperations;
Import Org.springframework.kafka.core.KafkaTemplate;
Import Org.springframework.kafka.support.ProducerListener;
Import org.springframework.stereotype.Component; /** * Message producer * @author XIAOJF 2017/3/24 14:36 * * * @Component public class Msgproducer {@Autowired private Kafkat
Emplate<string,string> kafkatemplate;
public void Send () {kafkatemplate.send ("My-replicated-topic", "XIAOJF");
Kafkatemplate.send ("My-replicated-topic", "XIAOJF");
Kafkatemplate.metrics ();
Kafkatemplate.execute (New kafkaoperations.producercallback<string, String, object> () {@Override Public Object Doinkafka (producer<string, string> Producer) {//Here you can write Kafka native API operations return null;
}
}); Listener for message sending, for callback return information Kafkatemplate.setproducerlistener (new producerlistener<string, string> () {@ Override public void onsuccess (string topic, Integer partition, string key, String value, Recordmetadata Recor Dmetadata) {} @Override public void OnError (string topic, Integer partition, string Key, String value, Exception Exception) {} @Override public boolean Isinterestedin
Success () {return false;
}
}); }
}
Message Consumers
Package Cn.xiaojf.today.data.kafka.consumer;
Import Org.springframework.kafka.annotation.KafkaListener;
Import org.springframework.stereotype.Component;
/**
* Message Consumer
* @author XIAOJF 2017/3/24 14:36
/
@Component public
class Msgconsumer {
@ Kafkalistener (topics = {"My-replicated-topic", "My-replicated-topic2"}) public
void ProcessMessage (String Content) {
System.out.println (content);
}
}