kafka与spring的整合

阅读更多
首先导入两个包:

org.apache.kafka
kafka-clients
0.10.0.0



org.springframework.kafka
spring-kafka
1.0.5.RELEASE


一个kafkaClient包,一个spring整合包。

然后建立生产者配置文件:
kafka_producer.xml


    
	
		
			
				
				
				
				
				
				
				
				
			
		
	
     
	
		
			
		
	
    
	
		
		
		
		
	
    
	

 


然后是消费者配置文件:



    
	
		
			
				
				
				
				
				
				
				
			
		
	
      
	
		
			
		
	
	
	
	
	 
      
          
          
      
     
      
          
          
      


建立测试类:
@Component
public class KafkaServer {
	@Autowired
	private KafkaTemplate kafkaTemplate;

	public void sendMessage(String topic, String key, Object value) {
		kafkaTemplate.setProducerListener(new KafkaProducerListener());
		ListenableFuture> f = kafkaTemplate.send(topic, key, JSON.toJSONString(value));
		try {
			System.out.println(f.get().getProducerRecord().key());
			System.out.println(f.get().getProducerRecord().value());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		System.out.println("发送了消息成功");

	}

	public static void main(String[] args) {
		ApplicationContext applicationContext = new FileSystemXmlApplicationContext("classpath:applicationContext.xml");
		KafkaServer server = (KafkaServer) applicationContext.getBean("kafkaServer");
		RoleBean bean = new RoleBean();
		bean.setDm("test");
		bean.setMc("测试2");
		server.sendMessage("linlin", "test", bean);
	}
}

public class KafkaConsumerListener implements MessageListener{

	@Override
	public void onMessage(ConsumerRecord record) {
		System.out.println("消费 ——————————————————————————");
        System.out.println(record.key()); 
        System.out.println(record.value());
	}

}

public class KafkaProducerListener  extends ProducerListenerAdapter {

	@Override
	public void onSuccess(String topic, Integer partition, K key, V value, RecordMetadata recordMetadata) {
		System.out.println("topic___________________________"+topic);
		System.out.println("key______________________________"+key);
		System.out.println("value___________________________"+value);
		System.out.println("发送成功");
	}

	@Override
	public void onError(String topic, Integer partition, K key, V value, Exception exception) {
		System.out.println("发送失败");
	}

	@Override
	public boolean isInterestedInSuccess() {
		return true;
	}

}


你可能感兴趣的:(kafka)