kafka

springboot 整合 kafka 如何实现消息路由

小樊
81
2024-12-14 21:55:24
栏目: 大数据

在 Spring Boot 中整合 Kafka 并实现消息路由,你需要遵循以下步骤:

  1. 添加依赖

在你的 Spring Boot 项目的 pom.xml 文件中,添加 Kafka 和 Spring Kafka 的依赖:

<dependencies>
    <!-- Spring Kafka -->
    <dependency>
        <groupId>org.springframework.kafka</groupId>
        <artifactId>spring-kafka</artifactId>
    </dependency>
    <!-- Kafka Client -->
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-clients</artifactId>
    </dependency>
</dependencies>
  1. 配置 Kafka

application.propertiesapplication.yml 文件中,配置 Kafka 的相关参数:

# application.properties
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=my-group
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer

spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
  1. 创建消息路由配置类

创建一个配置类,用于定义消息路由规则。在这个类中,你需要使用 @Bean 注解来创建一个 KafkaListenerEndpointRegistry 实例,并注册你的消息监听器。

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.KafkaListenerConfigurer;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerEndpointRegistrar;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
import org.springframework.kafka.listener.config.MethodKafkaListenerEndpoint;
import org.springframework.kafka.listener.config.MethodKafkaListenerEndpointRegistrar;
import org.springframework.kafka.support.serializer.ErrorHandlingDeserializer;
import org.springframework.kafka.support.serializer.JsonDeserializer;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class KafkaRouterConfig implements KafkaListenerConfigurer {

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        return factory;
    }

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerConfigs());
    }

    @Bean
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "my-group");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        return props;
    }

    @Override
    public void configureKafkaListeners(KafkaListenerEndpointRegistrar registrar) {
        MethodKafkaListenerEndpoint<String, String> endpoint = new MethodKafkaListenerEndpoint<>();
        endpoint.setId("myListener");
        endpoint.setTopics("my-topic");
        endpoint.setMessageHandlerMethodFactory(kafkaListenerContainerFactory());
        endpoint.setBean(new MyKafkaMessageListener());
        registrar.registerEndpoint(endpoint);
    }

    @Bean
    public KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry() {
        return new KafkaListenerEndpointRegistry();
    }
}
  1. 创建消息监听器

创建一个类,用于处理接收到的消息。在这个类中,你需要使用 @KafkaListener 注解来定义一个方法,该方法将在接收到消息时被调用。

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@Component
public class MyKafkaMessageListener {

    @KafkaListener(id = "myListener", topics = "my-topic")
    public void listen(String message) {
        System.out.println("Received message: " + message);
        // 根据消息内容进行路由处理
    }
}
  1. 发送消息

现在你可以使用 Kafka Producer 发送消息到指定的主题。在你的服务类中,注入 KafkaTemplate 并使用它发送消息。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
public class MyKafkaProducer {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    public void sendMessage(String topic, String message) {
        kafkaTemplate.send(topic, message);
    }
}

通过以上步骤,你已经成功地在 Spring Boot 项目中整合了 Kafka,并实现了消息路由。当你的应用程序接收到消息时,MyKafkaMessageListener 类中的 listen 方法将被调用,你可以在这个方法中根据消息内容进行相应的处理。

0
看了该问题的人还看了