本地Docker部署Pulsar訊息代理實現訊息釋出和訊息訂閱
介紹
實踐步驟
1.使用dokcer本地部署pulsar
docker run -it \ -p 6650:6650 \ -p 8080:8080 \ --mount source=pulsardata,target=/pulsar/data \ --mount source=pulsarconf,target=/pulsar/conf \ apachepulsar/pulsar:2.7.1 \ bin/pulsar standalone
2.docker ps -a 檢視pulsar執行是否正常,可以看到下圖已經部署成功
pulsar連線地址:http://localhost:8080
3.使用C#客戶端Publish Message到pulsar broker中
(1)為了演示,我這裡建立了一個C#控制檯專案
(2)我們使用官網推薦的C# pulsar客戶端包,新增安裝DotPulsar nuget包
(3)建立client
//1。建立pulsar客戶端 var client = PulsarClient.Builder() .ServiceUrl(new Uri("pulsar://localhost:6650")) .RetryInterval(new TimeSpan(3)) .Build();
(4)建立生產者,傳送訊息
//2、建立Pulsar Producer(生產者) var producer = client.NewProducer() .Topic("persistent://public/default/mytopic") .Create(); var data = Encoding.UTF8.GetBytes("Hello Pulsar"); await producer.Send(data);
上圖可見顯示建立producer成功。
(5)下面再建立一個客戶端來消費傳送者傳送的訊息(“Hello Pulsar”)。
//2、建立Pulsar Producer(消費者) var consumer = client.NewConsumer() .SubscriptionName("MySubscription") .Topic("persistent://public/default/mytopic") .Create(); //3.消費訊息 await foreach (var message in consumer.Messages()) { Console.WriteLine("Received: " + Encoding.UTF8.GetString(message.Data.ToArray())); }
見上圖,釋出者傳送訊息成功被訂閱者消費。
4.程式碼示例
//PublisherClient static async Task Main(string[] args) { Console.WriteLine("Hello Pulsar"); //1。建立pulsar客戶端 var client = PulsarClient.Builder() .ServiceUrl(new Uri("pulsar://localhost:6650")) .RetryInterval(new TimeSpan(3)) .Build(); //2、建立Pulsar Producer(生產者) var producer = client.NewProducer() .Topic("persistent://public/default/mytopic") .Create(); for (int i = 0; i < 5; i++) { var data = Encoding.UTF8.GetBytes($"Hello Pulsar {i}"); await producer.Send(data); Console.WriteLine($"傳送訊息成功"); } Console.ReadKey(); } //SubscriberClient static async Task Main(string[] args) { //1。建立pulsar客戶端 var client = PulsarClient.Builder() .ServiceUrl(new Uri("pulsar://localhost:6650")) .RetryInterval(new TimeSpan(3)) .Build(); //2、建立Pulsar Producer(消費者) var consumer = client.NewConsumer() .SubscriptionName("MySubscription") .Topic("persistent://public/default/mytopic") .Create(); //3.消費訊息 await foreach (var message in consumer.Messages()) { Console.WriteLine("Received: " + Encoding.UTF8.GetString(message.Data.ToArray())); } Console.ReadKey(); }