首先推荐一篇大佬的文章,看完之后,应该就对kafka有了基本的了解
《大佬的文章》
--------------------------进入正题-----------------------------
- pom.xml(导入依赖)
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>1.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
- 构建实体类
@Data
public class Student{
private String id;
private String name;
}
- 发布
@Slf4j
@Component
public class KafkaProducer(){
@AutoWire
private KafkaTemplate kafkaTemplate;
private static void final TOPIC_TEST="studentMessage"
public void send(Student student){
//注意:kafka只能发布String类型
LinstenableFuture<SendResult<String,Object>> send = kafkaTemplate.send(TOPIC_TEST, JsonUitl.toJsonStr(student));
send.addCallback(new ListenableFutureCallback<SendResult<String,Object>>(){
@Override
public void onFailure(Throwable throwable){
log.error(TOPIC_TEST+"-生产者发送消息失败,失败详情为:"+throwable.getMessage());
}
@Override
public void onSuccess(SendResult<String,Object>> stringObjectSendResult){
log.error(TOPIC_TEST+"-生产者发送消息成功,信息详情为:"+JsonUitl.toJsonStr(student));
}
});
}
}
- 订阅
@KafkaListener(topics = {"studentMessage"}
public void listener(ConsumerRecord<String,String> record){
@AutoWired
private SimpMessagingTemplate simMessagingTemplate;
String studentMessage = record.value();
HashMap map = JSONObject.parseObject(studentMessage,HashMap.class);
System.out.println(sutdentMessage);
//发送到websocket
simMessagingTemplate.convertAndSend("sutdent/"+map.get("id"),studentMessage);
}