title: Pulsar Pythonクライアント tags_ja:
PythonクライアントライブラリはC++クライアントライブラリのラッパーで全ての同じ機能を公開しています。C++クライアントコードの[python
サブディレクトリ]({{ site.pulsar_repo }}/pulsar-client-cpp/python)内にコードがあります。
pipを利用するかソースコードからライブラリをビルドすることでpulsar-client
をインストールできます。
pipを利用してのインストール:
$ pip install pulsar-client
ソースコードからビルドしてのインストールは、説明にしたがってC++クライアントライブラリをコンパイルします。これによりライブラリ用のPythonバインディングもビルドされます。
ビルドされたPythonバインディングのインストール:
$ git clone https://github.com/apache/pulsar $ cd pulsar/pulsar-client-cpp/python $ sudo python setup.py install
{% include admonition.html type=“info” content=“現在サポートされているPythonのバージョンは2.7のみです” %}
完全なPython APIのリファレンスはapi/pythonにあります。
以下にpulsar-client
ライブラリのPythonコード例を示します。
このコードはpersistent://sample/standalone/ns/my-topic
用のPython {% popover_ja Producer %}を作成し、10個のメッセージを送信します:
import pulsar client = pulsar.Client('pulsar://localhost:6650') producer = client.create_producer( 'persistent://sample/standalone/ns/my-topic') for i in range(10): producer.send('Hello-%d' % i) client.close()
このコードはpersistent://sample/standalone/ns/my-topic
トピック上にmy-sub
サブスクリプションで {% popover_ja Consumer %}を作成し、メッセージを待ち受けます。受け取ったメッセージの中身とIDを出力し、Pulsar {% popover_ja Broker %}に{% popover Ack %} (確認応答) を返します:
import pulsar client = pulsar.Client('pulsar://localhost:6650') consumer = client.subscribe( 'persistent://sample/standalone/ns/my-topic', 'my-sub') while True: msg = consumer.receive() print("Received message '%s' id='%s'", msg.data(), msg.message_id()) consumer.acknowledge(msg) client.close()
このコードは非同期でメッセージを送信する{% popover Producer %}を作成し、 {% popover Broker %}から{% popover Ack %} (確認応答) を受け取る度にsend_callback
コールバック関数を呼びます:
import pulsar client = pulsar.Client('pulsar://localhost:6650') producer = client.create_producer( 'persistent://sample/standalone/ns/my-topic', block_if_queue_full=True, batching_enabled=True, batching_max_publish_delay_ms=10 ) def send_callback(res, msg): print('Message published res=%s', res) while True: producer.send_async('Hello-%d' % i, send_callback) client.close()