代码之家  ›  专栏  ›  技术社区  ›  user5906464

如何通过web服务器作为中间层将Kafka消费者集成到移动应用程序?

  •  1
  • user5906464  · 技术社区  · 7 年前

    我真的不知道如何在后端使用websocket并将其集成到移动应用程序中。

    卡夫卡制作人:

    bin/kafka-console-producer.sh --broker-list localhost:9092 --topic Hello-Kafka
    

    消费者py:

    from kafka import KafkaConsumer
    from flask import Flask
    import json
    
    new_msg = ""
    app = Flask(__name__)
    @app.route('/')
    def hello_world():
         return new_msg
    
    consumer = KafkaConsumer('Hello-Kafka',bootstrap_servers='localhost:9092')
    for msg in consumer:
        if(len(msg.value.decode("utf-8"))!=0):
            new_msg = msg.value.decode("utf-8")
            app.run()
    
    kafkaConsumer(value_deserializer=lambda m: json.loads(m.decode('ascii')))
    

    mobileapp。swift:

    import UIKit
    
    class ViewController: UIViewController {
    
        let myNotification = Notification.Name(rawValue:"MyNotification")
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let nc = NotificationCenter.default
            nc.addObserver(forName:myNotification, object:nil, queue:nil, using:catchNotification)
        }
    
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
            let nc = NotificationCenter.default
            nc.post(name:myNotification,
                    object: nil,
                    userInfo:["message":"Hello there!", "date":Date()])
        }
    
        func catchNotification(notification:Notification) -> Void {
            print("Catch notification")
    
            guard let userInfo = notification.userInfo,
                let message  = userInfo["message"] as? String,
                let date     = userInfo["date"]    as? Date else {
                    print("No userInfo found in notification")
                    return
            }
    
            let alert = UIAlertController(title: "Notification!",
                                          message:"\(message) received at \(date)",
                preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
    

    现在,在消费了卡夫卡之后,我只能向浏览器发送一条消息。如何将其集成到移动应用程序中,以便我可以将我消费的每一条消息发送到该应用程序中?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Hans Jespersen    7 年前

    您可能需要考虑使用Kafka到websocket的现有代理/网关实现之一,例如Microsoft的websocket代理 https://github.com/Microsoft/kafka-proxy-ws 或Landoop提供的基于Akka Http WebSocket的服务 https://github.com/Landoop/kafka-ws