kafka

roducer=KafkaProducer(bootstra_servers=['10.1.1.1:9000,'4.4.4.4:8888'],
		security_protocol='SASL_PLAINTEXT',
		value_serializer=lambda v:json.dumps(v).encode('utf-8')
		sasl_mechanism='SCRAM-SHA-256',
		sasl_kerberos_service_name='target'
		sasl_plain_username="ee”。
		sasl_plain_password="eres",
		api_version(2,3,0)用这些信息使用java实现给kafka的多个ip和端口发送报文格式是{
"router_key":"name",
"prod_type":23,
"branch":"vere",
"even_type":"CERT",
"ccy":"CNY",
"profit":"B",
"cercore":"TT"
}怎样写一个应用服务启动服务传报文执行发送

要在Java中实现一个Kafka生产者应用服务,并接收POST请求发送JSON报文到Kafka,可以按照以下步骤操作:

  1. 引入必要的依赖: 在你的pom.xml文件中添加Kafka客户端库和Spring Boot相关依赖:

    xml

    <dependencies>
        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>
    </dependencies>
    

  2. 配置Kafka生产者: 创建一个配置类,用于配置Kafka生产者的属性。

    java

    import org.apache.kafka.clients.producer.ProducerConfig;
    import org.apache.kafka.common.config.SaslConfigs;
    import org.apache.kafka.common.serialization.StringSerializer;
    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.ErrorHandlingDeserializer;
    import org.springframework.kafka.support.serializer.JsonDeserializer;
    import org.springframework.kafka.support.serializer.JsonSerializer;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @Configuration
    public class KafkaProducerConfig {
    
        @Bean
        public ProducerFactory<String, Object> producerFactory() {
            Map<String, Object> configProps = new HashMap<>();
            configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "10.1.1.1:9000,4.4.4.4:8888");
            configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
            configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
            configProps.put("security.protocol", "SASL_PLAINTEXT");
            configProps.put(SaslConfigs.SASL_MECHANISM, "SCRAM-SHA-256");
            configProps.put(SaslConfigs.SASL_JAAS_CONFIG,
                    "org.apache.kafka.common.security.scram.ScramLoginModule required username=\"ee\" password=\"eres\";");
            configProps.put(ProducerConfig.ACKS_CONFIG, "all");
    
            return new DefaultKafkaProducerFactory<>(configProps);
        }
    
        @Bean
        public KafkaTemplate<String, Object> kafkaTemplate() {
            return new KafkaTemplate<>(producerFactory());
        }
    }
    

  3. 创建REST控制器: 创建一个Spring Boot的REST控制器,用于接收POST请求并将数据发送到Kafka。

    java

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.kafka.core.KafkaTemplate;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/api")
    public class KafkaProducerController {
    
        @Autowired
        private KafkaTemplate<String, Object> kafkaTemplate;
    
        @PostMapping("/send")
        public String sendMessage(@RequestBody Map<String, Object> message) {
            kafkaTemplate.send("your_topic", message);
            return "Message sent to Kafka";
        }
    }
    

  4. 启动应用: 创建Spring Boot的主应用类。

    java

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class KafkaProducerApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(KafkaProducerApplication.class, args);
        }
    }
    

  5. 运行并测试: 启动你的Spring Boot应用,使用工具如Postman发送一个POST请求到http://localhost:8080/api/send,请求体为JSON格式:

    json

    {
        "router_key": "name",
        "prod_type": 23,
        "branch": "vere",
        "even_type": "CERT",
        "ccy": "CNY",
        "profit": "B",
        "cercore": "TT"
    }
    

    这将把JSON数据发送到指定的Kafka topic。

请确保将Kafka broker地址、topic名称等替换为你的实际配置。这样,你的应用服务就可以接收JSON报文并发送到Kafka了

上面的想修改端口怎么修改,还有把topic作为参数传递过去

为了能够在运行时修改Kafka broker地址和端口,并且将topic作为参数传递到发送消息的方法中,你可以采取以下步骤:

  1. 使用Spring Boot的配置文件: 将Kafka broker地址配置到application.properties文件中,这样可以更方便地进行修改。

    src/main/resources/application.properties中添加:

    properties

    kafka.bootstrap-servers=10.1.1.1:9000,4.4.4.4:8888
    kafka.security-protocol=SASL_PLAINTEXT
    kafka.sasl-mechanism=SCRAM-SHA-256
    kafka.sasl-username=ee
    kafka.sasl-password=eres
    

  2. 修改KafkaProducerConfig类: 使用Spring Boot的@Value注解从配置文件中读取这些值。

    import org.apache.kafka.clients.producer.ProducerConfig;
    import org.apache.kafka.common.config.SaslConfigs;
    import org.apache.kafka.common.serialization.StringSerializer;
    import org.springframework.beans.factory.annotation.Value;
    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 java.util.HashMap;
    import java.util.Map;
    
    @Configuration
    public class KafkaProducerConfig {
    
        @Value("${kafka.bootstrap-servers}")
        private String bootstrapServers;
    
        @Value("${kafka.security-protocol}")
        private String securityProtocol;
    
        @Value("${kafka.sasl-mechanism}")
        private String saslMechanism;
    
        @Value("${kafka.sasl-username}")
        private String saslUsername;
    
        @Value("${kafka.sasl-password}")
        private String saslPassword;
    
        @Bean
        public ProducerFactory<String, Object> producerFactory() {
            Map<String, Object> configProps = new HashMap<>();
            configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
            configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
            configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
            configProps.put("security.protocol", securityProtocol);
            configProps.put(SaslConfigs.SASL_MECHANISM, saslMechanism);
            configProps.put(SaslConfigs.SASL_JAAS_CONFIG,
                    String.format("org.apache.kafka.common.security.scram.ScramLoginModule required username=\"%s\" password=\"%s\";",
                            saslUsername, saslPassword));
            configProps.put(ProducerConfig.ACKS_CONFIG, "all");
    
            return new DefaultKafkaProducerFactory<>(configProps);
        }
    
        @Bean
        public KafkaTemplate<String, Object> kafkaTemplate() {
            return new KafkaTemplate<>(producerFactory());
        }
    }
    

  3. 修改KafkaProducerController类: 在发送消息的方法中添加topic作为参数。

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.kafka.core.KafkaTemplate;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.Map;
    
    @RestController
    @RequestMapping("/api")
    public class KafkaProducerController {
    
        @Autowired
        private KafkaTemplate<String, Object> kafkaTemplate;
    
        @PostMapping("/send")
        public String sendMessage(@RequestParam String topic, @RequestBody Map<String, Object> message) {
            kafkaTemplate.send(topic, message);
            return "Message sent to Kafka topic: " + topic;
        }
    }
    

  4. 启动应用并测试: 启动Spring Boot应用后,使用工具如Postman发送一个POST请求到http://localhost:8080/api/send?topic=your_topic,请求体为JSON格式:

    {
        "router_key": "name",
        "prod_type": 23,
        "branch": "vere",
        "even_type": "CERT",
        "ccy": "CNY",
        "profit": "B",
        "cercore": "TT"
    }
    

    这将把JSON数据发送到你指定的Kafka topic。

通过以上步骤,你可以轻松地修改Kafka的端口和将topic作为参数传递给发送消息的方法。

上面的怎么部署到linux上,端口想设置为8090怎么设置

要将上述Spring Boot应用部署到Linux服务器上并将其端口设置为8090,可以按照以下步骤操作:

  1. 构建Spring Boot应用: 先在本地构建你的Spring Boot应用的可执行JAR文件。在你的项目根目录下运行以下命令:

    sh./mvnw clean package 

    这将生成一个可执行的JAR文件,通常在target目录下,如target/myapp-0.0.1-SNAPSHOT.jar

  2. 将JAR文件上传到Linux服务器: 使用scp或其他文件传输工具将生成的JAR文件上传到Linux服务器上的某个目录,例如/opt/myapp/

    shscp target/myapp-0.0.1-SNAPSHOT.jar user@your_linux_server:/opt/myapp/ 
  3. 配置Spring Boot应用端口: 在Linux服务器上创建一个application.properties文件,并将端口设置为8090:

    properties

    server.port=8090
    
    kafka.bootstrap-servers=10.1.1.1:9000,4.4.4.4:8888
    kafka.security-protocol=SASL_PLAINTEXT
    kafka.sasl-mechanism=SCRAM-SHA-256
    kafka.sasl-username=ee
    kafka.sasl-password=eres
    

    将此文件放置在应用程序的同一目录中(例如/opt/myapp/)。

  4. 运行Spring Boot应用: 使用以下命令在后台运行Spring Boot应用:

    cd /opt/myapp
    nohup java -jar myapp-0.0.1-SNAPSHOT.jar --spring.config.location=/opt/myapp/application.properties > myapp.log 2>&1 &
    

    这将使用指定的配置文件启动应用,并将日志输出到myapp.log文件中。

  5. 验证应用是否运行: 可以使用以下命令检查应用是否在运行:

    sh

    ps aux | grep myapp-0.0.1-SNAPSHOT.jar
    

    或检查日志文件:

    sh

    tail -f /opt/myapp/myapp.log
    

  6. 配置防火墙: 确保Linux服务器的防火墙允许8090端口的流量。使用以下命令打开8090端口(具体命令可能因Linux发行版而异):

    sudo ufw allow 8090/tcp
    sudo ufw reload
    

    或者,如果使用的是iptables

    sudo iptables -A INPUT -p tcp --dport 8090 -j ACCEPT
    

    确保保存防火墙规则,以便重启后规则依然生效。

  7. 测试应用: 使用浏览器或工具如Postman发送请求到你的应用,例如:

    http://your_linux_server:8090/api/send?topic=your_topic
    

    并使用JSON格式的请求体。

通过这些步骤,你可以在Linux服务器上部署Spring Boot应用,并将其端口设置为8090。

想用nohup java -jar的方式不要用--spring.config.location=/opt/myapp/application.properties这个信息怎么做

如果你不想使用--spring.config.location参数指定配置文件,而是将配置文件直接打包到JAR文件中并使用nohup java -jar运行应用程序,你可以按照以下步骤操作:

  1. 将配置文件打包到JAR文件中: 确保你的application.properties文件位于src/main/resources目录中,这样在构建时会自动被打包到JAR文件中。

    csssrc/main/resources/application.properties 
  2. 修改配置文件: 在src/main/resources/application.properties文件中添加或修改配置,以便Spring Boot应用程序在启动时读取这些配置。

    server.port=8090
    
    kafka.bootstrap-servers=10.1.1.1:9000,4.4.4.4:8888
    kafka.security-protocol=SASL_PLAINTEXT
    kafka.sasl-mechanism=SCRAM-SHA-256
    kafka.sasl-username=ee
    kafka.sasl-password=eres
    

  3. 构建Spring Boot应用: 在项目根目录下运行以下命令,以生成包含配置文件的可执行JAR文件:

    sh./mvnw clean package 
  4. 将JAR文件上传到Linux服务器: 使用scp或其他文件传输工具将生成的JAR文件上传到Linux服务器上的某个目录,例如/opt/myapp/

    shscp target/myapp-0.0.1-SNAPSHOT.jar user@your_linux_server:/opt/myapp/ 
  5. 运行Spring Boot应用: 使用以下命令在后台运行Spring Boot应用:

    cd /opt/myapp
    nohup java -jar myapp-0.0.1-SNAPSHOT.jar > myapp.log 2>&1 &
    

    这将使用打包到JAR文件中的配置文件启动应用,并将日志输出到myapp.log文件中。

  6. 验证应用是否运行: 可以使用以下命令检查应用是否在运行:

    shps aux | grep myapp-0.0.1-SNAPSHOT.jar 

    或检查日志文件:

    shtail -f /opt/myapp/myapp.log 
  7. 配置防火墙: 确保Linux服务器的防火墙允许8090端口的流量。使用以下命令打开8090端口(具体命令可能因Linux发行版而异):

    sudo ufw allow 8090/tcp
    sudo ufw reload
    

    或者,如果使用的是iptables

    shsudo iptables -A INPUT -p tcp --dport 8090 -j ACCEPT 

    确保保存防火墙规则,以便重启后规则依然生效。

  8. 测试应用: 使用浏览器或工具如Postman发送请求到你的应用,例如:

    shhttp://your_linux_server:8090/api/send?topic=your_topic 

    并使用JSON格式的请求体。

通过这些步骤,你可以在Linux服务器上部署Spring Boot应用,并将其端口设置为8090,无需使用--spring.config.location参数。

本地启动提示 Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package是什么问题

出现“Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package”提示,通常是因为你的Spring Boot主类位于默认包中(即,没有显式声明包名)。为了避免这个问题,你需要确保所有的类(包括你的主类)都在一个明确声明的包中。

这里是解决该问题的步骤:

  1. 确保主类位于非默认包中: 确保你的主类(包含@SpringBootApplication注解的类)位于某个包中。例如,将它放在com.example.myapp包中。

    package com.example.myapp;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class KafkaProducerApplication {
        public static void main(String[] args) {
            SpringApplication.run(KafkaProducerApplication.class, args);
        }
    }
    

  2. 将其他类移动到相应的包中: 确保你的配置类和控制器类也位于这个包或其子包中。例如:

    package com.example.myapp.config;
    
    import org.apache.kafka.clients.producer.ProducerConfig;
    import org.apache.kafka.common.config.SaslConfigs;
    import org.apache.kafka.common.serialization.StringSerializer;
    import org.springframework.beans.factory.annotation.Value;
    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 java.util.HashMap;
    import java.util.Map;
    
    @Configuration
    public class KafkaProducerConfig {
    
        @Value("${kafka.bootstrap-servers}")
        private String bootstrapServers;
    
        @Value("${kafka.security-protocol}")
        private String securityProtocol;
    
        @Value("${kafka.sasl-mechanism}")
        private String saslMechanism;
    
        @Value("${kafka.sasl-username}")
        private String saslUsername;
    
        @Value("${kafka.sasl-password}")
        private String saslPassword;
    
        @Bean
        public ProducerFactory<String, Object> producerFactory() {
            Map<String, Object> configProps = new HashMap<>();
            configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
            configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
            configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
            configProps.put("security.protocol", securityProtocol);
            configProps.put(SaslConfigs.SASL_MECHANISM, saslMechanism);
            configProps.put(SaslConfigs.SASL_JAAS_CONFIG,
                    String.format("org.apache.kafka.common.security.scram.ScramLoginModule required username=\"%s\" password=\"%s\";",
                            saslUsername, saslPassword));
            configProps.put(ProducerConfig.ACKS_CONFIG, "all");
    
            return new DefaultKafkaProducerFactory<>(configProps);
        }
    
        @Bean
        public KafkaTemplate<String, Object> kafkaTemplate() {
            return new KafkaTemplate<>(producerFactory());
        }
    }
    
    package com.example.myapp.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.kafka.core.KafkaTemplate;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.Map;
    
    @RestController
    @RequestMapping("/api")
    public class KafkaProducerController {
    
        @Autowired
        private KafkaTemplate<String, Object> kafkaTemplate;
    
        @PostMapping("/send")
        public String sendMessage(@RequestParam String topic, @RequestBody Map<String, Object> message) {
            kafkaTemplate.send(topic, message);
            return "Message sent to Kafka topic: " + topic;
        }
    }
    

  3. 检查项目结构: 确保你的项目结构类似于以下结构:

    src/main/java
    └── com
        └── example
            └── myapp
                ├── KafkaProducerApplication.java
                ├── config
                │   └── KafkaProducerConfig.java
                └── controller
                    └── KafkaProducerController.java
    src/main/resources
        └── application.properties
    

这样可以确保Spring Boot能够正确地扫描并找到所有组件。

按照这些步骤,重新运行你的Spring Boot应用,应该可以解决这个问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值