ssm整合kafka
时间: 2023-10-18 15:06:19 浏览: 114
要在SSM框架中整合Kafka,需要进行以下步骤:
1. 在pom.xml文件中添加Kafka依赖:
```
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>2.8.0</version>
</dependency>
```
2. 在Spring配置文件中配置Kafka相关的Bean:
```
<bean id="kafkaProducerFactory" class="org.springframework.kafka.core.DefaultKafkaProducerFactory">
<constructor-arg>
<map>
<entry key="bootstrap.servers" value="localhost:9092" />
<entry key="key.serializer" value="org.apache.kafka.common.serialization.StringSerializer" />
<entry key="value.serializer" value="org.apache.kafka.common.serialization.StringSerializer" />
</map>
</constructor-arg>
</bean>
<bean id="kafkaTemplate" class="org.springframework.kafka.core.KafkaTemplate">
<constructor-arg ref="kafkaProducerFactory" />
</bean>
<bean id="kafkaListenerContainerFactory" class="org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory">
<property name="consumerFactory">
<bean class="org.springframework.kafka.core.DefaultKafkaConsumerFactory">
<constructor-arg>
<map>
<entry key="bootstrap.servers" value="localhost:9092" />
<entry key="key.deserializer" value="org.apache.kafka.common.serialization.StringDeserializer" />
<entry key="value.deserializer" value="org.apache.kafka.common.serialization.StringDeserializer" />
<entry key="group.id" value="test-group" />
</map>
</constructor-arg>
</bean>
</property>
</bean>
```
3. 在代码中使用KafkaTemplate发送消息:
```
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String message) {
kafkaTemplate.send("test-topic", message);
}
```
4. 在代码中使用@KafkaListener注解监听消息:
```
@KafkaListener(topics = "test-topic", groupId = "test-group")
public void receiveMessage(String message) {
System.out.println("Received message: " + message);
}
```
阅读全文