美文网首页
springboot整合kafka 30

springboot整合kafka 30

作者: 张力的程序园 | 来源:发表于2021-02-08 21:38 被阅读0次

1、环境约束

  • win10 64位操作系统
  • idea2018.1.5
  • maven-3.0.5
  • jdk-8u162-windows-x64

2、前提约束

2、操作步骤

  • 加入依赖
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>
  • 修改配置文件
server.port=8080
spring.kafka.bootstrap-servers=localhost:9092
# 指定默认消费者group id
spring.kafka.consumer.group-id=group-id
  • 创建生产者
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.RestController;

@RestController
public class Producer {
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @GetMapping("/send/{msg}")
    public void sendlog(@PathVariable("msg")String msg){

        kafkaTemplate.send("test",msg);

    }
}
  • 创建消费者
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@Component
public class Consumer {
    @KafkaListener(topics = {"test"})
    public  void consumer(ConsumerRecord consumerRecord){
        Object value = consumerRecord.value();
        System.out.println(value);
    }
}
  • 启动boot项目,在浏览器中访问http://localhost:8080/send/ali,在命令行中就能看到以下输出:
    消费者打印字符串
    以上就是springboot中整合kafka的过程。

相关文章

网友评论

      本文标题:springboot整合kafka 30

      本文链接:https://www.haomeiwen.com/subject/kzbfxltx.html