我对Springboot和Kafka非常陌生。在使用Springboot应用程序进行学校作业时,我们需要发布有关Kafka主题的Json数据。我发布的.java文件如下所示:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.CMPE172.kafka.springbootkafkaproducerexample.model.User;
@RestController
@RequestMapping("kafka")
public class UserResource {
@Autowired
private KafkaTemplate<String, User> kafkaTemplate;
private final static String TOPIC = "Kafka";
@GetMapping("/publish/{name}")
public String Post(@PathVariable("name") final String name) {
kafkaTemplate.send(TOPIC, new User(name, "Technology", 12000L));
return "Published successfully";
}
}
User仅是具有构造函数,getter和setter的普通Java类。 我的配置文件如下:
import org.apache.kafka.clients.producer.ProducerConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.support.serializer.JsonSerializer;
import com.CMPE172.kafka.springbootkafkaproducerexample.model.User;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Map;
import java.util.HashMap;
@Configuration
public class KafkaConfiguration {
@Bean
public ProducerFactory<String, User> produceFactory() {
Map<String, Object> config = new HashMap<>();
config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG , "127.0.0.1:9092");
config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG , StringSerializer.class);
config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG , JsonSerializer.class);
return new DefaultKafkaProducerFactory<>(config);
}
@Bean
public KafkaTemplate<String, User> kafkaTemplate() {
return new KafkaTemplate<>(produceFactory());
}
}
成功启动Zookeeper和Kafka服务器后,我使用以下命令创建新主题:
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions
1 --topic Kafka
然后我使用以下命令启动使用者:
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic Kafka --from-
beginning
然后我可以通过简单地转到localhost:8081 / kafka / publish / Adam来成功发布主题中的Json消息/对象(在这种情况下,将发布名称为Adam,部门“技术”和薪水为12000的Json对象)< / p>
问题/错误:每次我发布新名称时,第二次显示我先前发布的名称。例如,如果我转到localhost:8081 / kafka / publish / Jim,则包含Adam的Json文件将与Jim一起再次发布。此外,如果我重新启动所有服务器,则发布新的Json数据似乎会调用先前在服务器重新启动之前发布的发布名称。
长话短说,看看在线视频,每个出版物一次只能发布1个名字,别无其他。但是,就我而言,每个新出版物都会发布重复的值。有人能指出我正确的方向吗?所有帮助将不胜感激。预先谢谢你!
答案 0 :(得分:0)
您将附加到日志。每个请求都会创建一条全新的消息,而不是覆盖旧消息。
您拥有--from-beginning
的事实意味着您将始终从头开始扫描主题的每条消息,而不必等待新消息到达。
如果您确实认为有重复的消息要发布,则可以使用OffsetShell列出主题的最新偏移量