.net core 使用zookeeper

第一步:创建.net core 控制台引用

第二步:引用nuget包Rabbit.Zookeeper

 

 第三步:看代码

using org.apache.zookeeper;
using org.apache.zookeeper.data;
using Rabbit.Zookeeper;
using Rabbit.Zookeeper.Implementation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static org.apache.zookeeper.Watcher.Event;
using static org.apache.zookeeper.ZooDefs;

namespace zookeepercore
{
class Program
{
private static IZookeeperClient _client;

static async Task Main(string[] args)
{
_client = new ZookeeperClient(new ZookeeperClientOptions("ip:2181,ip:2182,ip:2183")
{
SessionTimeout = TimeSpan.FromSeconds(20),
OperatingTimeout = TimeSpan.FromSeconds(30)
});

//await GetChildrenAsyncTest();
//await ExistsAsyncTest();
//await GetDataAsyncTest();
//await CreateTest();
//await SubscribeDataChangeTest();
//await SubscribeChildrenChangeTest();
//await Test();
await MiaoShaTest();

Console.ReadLine();
}

static async Task Test()
{
var path = $"/C-20200415001";

Console.WriteLine("创建节点");
if (!await _client.ExistsAsync(path))
await _client.CreateEphemeralAsync(path, null);
Console.WriteLine("监听节点");
await _client.SubscribeDataChange(path, (client, args) =>
{
Console.WriteLine($"监听输出:{args.Type}({DateTime.Now.ToShortTimeString()})");
return Task.CompletedTask;
});

await Task.Factory.StartNew(() =>
{
while (true)
{
_client.SetDataAsync(path, new byte[] { 1 });
Thread.Sleep(1000);
}
});
}

public static async Task MiaoShaTest()
{
var nodePath = "/goods";
if (await _client.ExistsAsync(nodePath))
{
Console.WriteLine("没有找到节点");
return;
}
//创建5个线程抢三件商品
for (int i = 0; i < 5; i++)
{
Task.Factory.StartNew((index) =>
{
while (true)
{
//判断节点是否存在
var goods = _client.GetChildrenAsync(nodePath).Result;
if (goods == null || goods.Count() <= 0)
{
Console.WriteLine($"{index}线程{Thread.CurrentThread.ManagedThreadId}没抢到商品");
return;
}

try
{
var tempGoods = goods.First();
//删除商品节点,删除成功代表抢到商品
_client.DeleteAsync(nodePath + "/" + tempGoods).Wait();
Console.WriteLine($"{index}线程{Thread.CurrentThread.ManagedThreadId}抢到商品{tempGoods}");
return;
}
catch (Exception ex)
{
}
}

}, i);

}
}

/// <summary>
/// 获取节点
/// </summary>
/// <returns></returns>
public static async Task GetChildrenAsyncTest()
{
var childrens = await _client.GetChildrenAsync("/");

childrens = await _client.GetChildrenAsync("/ApiRouteRoot");
}

/// <summary>
/// 判断节点是否存在
/// </summary>
/// <returns></returns>
public static async Task ExistsAsyncTest()
{
var result = await _client.ExistsAsync("/ApiRouteRoot");
}

/// <summary>
/// 获取节点值
/// </summary>
/// <returns></returns>
public static async Task GetDataAsyncTest()
{
var data = await _client.GetDataAsync("/");

data = await _client.GetDataAsync("/config/");
}

public static async Task ReconnectionTest()
{
await _client.ExistsAsync("/");
await Task.Delay(TimeSpan.FromSeconds(8));
await _client.ExistsAsync("/");
}

/// <summary>
/// 创建节点并赋值
/// </summary>
/// <returns></returns>
public static async Task CreateTest()
{
var path = $"/{Guid.NewGuid():N}";

if (await _client.ExistsAsync(path))
await _client.DeleteAsync(path);

await _client.CreateEphemeralAsync(path, Encoding.UTF8.GetBytes("abc"));

var data = (await _client.GetDataAsync(path)).ToArray();
if (data != null)
{
var value = Encoding.UTF8.GetString(data);
}

if (await _client.ExistsAsync(path))
await _client.DeleteAsync(path);
}

/// <summary>
/// 订阅节点数据变化
/// </summary>
/// <returns></returns>
public static async Task SubscribeDataChangeTest()
{
var path = $"/{DateTime.Now:yyyy_MM_dd_HH_mm_ss_ff}";
try
{
if (await _client.ExistsAsync(path))
await _client.DeleteAsync(path);

var types = new List<EventType>();
var waitEvent = new AutoResetEvent(false);

await _client.SubscribeDataChange(path, (client, args) =>
{
types.Add(args.Type);
waitEvent.Set();
return Task.CompletedTask;
});

//created
await _client.CreateEphemeralAsync(path, null);
waitEvent.WaitOne(10000);

//modify
await _client.SetDataAsync(path, new byte[] { 1 });
waitEvent.WaitOne(10000);

//deleted
await _client.DeleteAsync(path);
waitEvent.WaitOne(10000);
}
finally
{
if (await _client.ExistsAsync(path))
await _client.DeleteAsync(path);
}
}

/// <summary>
/// 订阅子节点变化
/// </summary>
/// <returns></returns>
public static async Task SubscribeChildrenChangeTest()
{
var path = $"/{DateTime.Now:yyyy_MM_dd_HH_mm_ss_ff}";
var path2 = $"{path}/123";
var types = new List<Watcher.Event.EventType>();

try
{
if (await _client.ExistsAsync(path))
await _client.DeleteRecursiveAsync(path);

var semaphore = new Semaphore(0, 2);

await _client.SubscribeDataChange(path, (client, args) =>
{
if (args.Type == Watcher.Event.EventType.NodeCreated)
semaphore.Release();
return Task.CompletedTask;
});
await _client.SubscribeChildrenChange(path, (client, args) =>
{
types.Add(args.Type);
semaphore.Release();
return Task.CompletedTask;
});

await _client.CreatePersistentAsync(path, null);
semaphore.WaitOne(10000);
await _client.CreatePersistentAsync(path2, null);
semaphore.WaitOne(10000);
}
finally
{
if (await _client.ExistsAsync(path))
await _client.DeleteRecursiveAsync(path);
}
}

}
}

posted @ 2020-04-24 11:04  元点  阅读(1023)  评论(0编辑  收藏  举报