.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);
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构