Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring引导应用程序未使用kafka和restcontroller启动_Java_Spring_Spring Boot_Apache Kafka_Spring Restcontroller - Fatal编程技术网

Java Spring引导应用程序未使用kafka和restcontroller启动

Java Spring引导应用程序未使用kafka和restcontroller启动,java,spring,spring-boot,apache-kafka,spring-restcontroller,Java,Spring,Spring Boot,Apache Kafka,Spring Restcontroller,我有一个spring boot应用程序,在我的应用程序中包括Kafka consumer和producer之前,它运行良好。运行完全没有问题的代码有一个restController,如下所示: @RestController public class OrderResource { //Get orderheaderkeys for a particular date //OrderLine @GetMapping("/orderForDate/{forDate}")

我有一个spring boot应用程序,在我的应用程序中包括Kafka consumer和producer之前,它运行良好。运行完全没有问题的代码有一个restController,如下所示:

@RestController
public class OrderResource {
    //Get orderheaderkeys for a particular date
    //OrderLine
    @GetMapping("/orderForDate/{forDate}")
    public List<String> findOrderHeaderKeys(@PathVariable String forDate) {
        //Some business logic
        return keys;
    }
}
@RestController
公共类OrderResource{
//获取特定日期的orderheaderkeys
//订单线
@GetMapping(“/orderForDate/{forDate}”)
公共列表findOrderHeaderKeys(@PathVariable String forDate){
//一些商业逻辑
返回键;
}
}
这个休息终点给出了期望的响应。 现在,我包括卡夫卡制作人和消费者,他们看起来

@Component
public class KafkaProducerClient {
private static Logger logger = LoggerFactory.getLogger(KafkaProducerClient.class);
    private KafkaProducer<String, String> producer;

    @Value("${kafka.bootstrap.servers}")
    private String kafkaBootstrapServers;

    @PostConstruct
    public void init() {
        Properties properties = new Properties();
        properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaBootstrapServers);
        properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        producer = new KafkaProducer<String, String>(properties);
    }

    public void sendMessageAsync(String topic, String key, String jsonString) {
        logger.info("Sending message async to kafka topic with key = {}", key);
        long startTime = System.currentTimeMillis();
        ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, jsonString);

        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception exception) {
                final long timeTaken = System.currentTimeMillis() - startTime;
                if (recordMetadata != null) {
                    logger.info("Producer sent record(key={}, value={}). " +
                                    "Topic={}, Partition={}, Offset={}, timeTaken={}",
                            record.key(), record.value(), topic, recordMetadata.partition(),
                            recordMetadata.offset(), String.valueOf(timeTaken));
                }
                if (exception != null) {
                    logger.error("Exception occurred while posting message", exception.getMessage());
                    return;
                }
            }
        });
        logger.info("Message sent to kafka topic with key = {}", key);
    }

    public void sendMessageSync(String topic, String key, String jsonString) {
        try {
            logger.info("Sending message sync to kafka topic={} with key={}", topic, key);
            long startTime = System.currentTimeMillis();
            ProducerRecord<String, String> record = new ProducerRecord<String, String>(topic, key, jsonString);
            Future<RecordMetadata> future = producer.send(record);
            producer.flush();
            RecordMetadata recordMetadata = future.get();
            final long timeTaken = System.currentTimeMillis() - startTime;
            if (recordMetadata != null) {
                logger.info(
                        "Producer sent message by sendMessageSync. record={}. timeTaken={}",
                        recordMetadata,
                        String.valueOf(timeTaken));
            }
        } catch (Exception ex) {
            logger.error("Exception occured....", ex);
        }

    }

    @PreDestroy
    private void shutdown(){
        producer.close();
    }
}
@组件
公共类卡夫卡制作客户端{
私有静态记录器Logger=LoggerFactory.getLogger(KafkaProducerClient.class);
私人卡夫卡制作人;
@值(${kafka.bootstrap.servers}”)
私有字符串KafkabootStrapServer;
@施工后
公共void init(){
属性=新属性();
setProperty(ProducerConfig.BOOTSTRAP\u SERVERS\u CONFIG,kafkabootstrapserver);
properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,StringSerializer.CLASS.getName());
properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,StringSerializer.CLASS.getName());
制作人=新卡夫卡制作人(财产);
}
public void sendMessageAsync(字符串主题、字符串键、字符串jsonString){
info(“使用key={},key向kafka主题异步发送消息”);
long startTime=System.currentTimeMillis();
ProducerRecord记录=新的ProducerRecord(主题、键、jsonString);
producer.send(记录,新回调(){
@凌驾
公共void onCompletion(记录元数据记录元数据异常){
最终耗时=System.currentTimeMillis()-startTime;
if(recordMetadata!=null){
info(“生产者发送的记录(键={},值={})。”+
“主题={},分区={},偏移量={},时间={}”,
record.key()、record.value()、主题、recordMetadata.partition(),
recordMetadata.offset(),String.valueOf(timetake));
}
if(异常!=null){
logger.error(“发布消息时发生异常”,Exception.getMessage());
返回;
}
}
});
info(“用key={},key发送给kafka主题的消息);
}
public void sendMessageSync(字符串主题、字符串键、字符串jsonString){
试一试{
info(“发送消息同步到kafka topic={}和key={}”,topic,key);
long startTime=System.currentTimeMillis();
ProducerRecord记录=新的ProducerRecord(主题、键、jsonString);
Future=producer.send(记录);
producer.flush();
RecordMetadata RecordMetadata=future.get();
最终耗时=System.currentTimeMillis()-startTime;
if(recordMetadata!=null){
logger.info(
“生产者通过sendMessageSync.record={}.TimeTake={}发送消息”,
记录元数据,
String.valueOf(timetake));
}
}捕获(例外情况除外){
logger.error(“发生异常…”,例如);
}
}
@发情前期
私有无效关闭(){
producer.close();
}
}
@组件
公共类KafkaConsumerClient{
私有静态记录器Logger=LoggerFactory.getLogger(KafkaConsumerClient.class);
私人卡夫卡消费品;
@值(${kafka.bootstrap.servers}”)
私有字符串KafkabootStrapServer;
@值(${kafka.topic}”)
私有字符串主题;
@值(${zookeeper.groupId}”)
私有字符串groupId;
@施工后
公共void init(){
属性=新属性();
setProperty(ConsumerConfig.BOOTSTRAP\u SERVERS\u CONFIG,kafkabootstrapserver);
properties.setProperty(ConsumerConfig.KEY_反序列化器_CLASS_CONFIG,StringDeserializer.CLASS.getName());
properties.setProperty(ConsumerConfig.VALUE_反序列化程序_CLASS_CONFIG,StringDeserializer.CLASS.getName());
setProperty(ConsumerConfig.GROUP\u ID\u CONFIG,groupId);
消费者=新卡夫卡消费者(房产);
consumer.subscribe(Arrays.asList(topic));
while(true){
ConsumerRecords记录=consumer.poll(持续时间:百万分之一百);
对于(消费者记录:记录){
试一试{
logger.info(“Key:+record.Key()+”,Value:+record.Value());
//orderResource.saveOrderToSecondaryStore(record.value().toString());
}捕获(例外e){
logger.error(“处理卡夫卡消息时出现异常”,e);
}
}
}
}
}
包括这些消费者和生产者后,我的应用程序不会启动。我看不到以前在应用程序正常运行时显示的以下行

2019-12-12 15:01:12.090信息38376---[restartedMain]o.s.b.w.embedded.tomcat.TomcatWebServer:tomcat在端口8080(http)上启动,上下文路径为“”
2019-12-12 15:01:12.093 INFO 38376---[restartedMain]c.w.c.o.p.MySpringApplication:在15.187秒内启动MySpringApplication(JVM运行15.617)

我通过将消费者轮询(while循环)移到KafkaConsumerClient的init方法之外解决了这个问题

@PostConstruct
public void init() {
}

在Tomcat服务器上部署Spring引导应用程序: 更新pom.xml:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
更新卡夫卡依赖项和配置,了解更多详细信息,请访问下面的链接-

是否可以添加fu
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}