Skip to content

Instantly share code, notes, and snippets.

@patricksuo
Last active August 23, 2018 14:10
Show Gist options
  • Save patricksuo/93fc060c82159096cdf5e4043051e21e to your computer and use it in GitHub Desktop.
Save patricksuo/93fc060c82159096cdf5e4043051e21e to your computer and use it in GitHub Desktop.
using System;
using System.Text;
using Consul;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using System.Threading;
namespace TestApp
{
public static class Program
{
public static async void startWatchService(ConsulClient client, string key, BufferBlock<object> queue, CancellationToken cancellationToken)
{
var lastIndex = (ulong)0;
while (!cancellationToken.IsCancellationRequested)
{
try
{
var res = await client.KV.List(key, new QueryOptions() { WaitIndex = lastIndex }, cancellationToken);
lastIndex = res.LastIndex;
queue.Post("new services info");
}
catch (Exception)
{
Console.WriteLine($"get key failed when watch key {key}");
return;
}
}
}
private static void Main(string[] args)
{
var consulAddress = "http://127.0.0.1:8500";
if (args.Length > 0)
{
consulAddress = args[0];
}
var cancelSrc = new System.Threading.CancellationTokenSource();
var queue = new BufferBlock<object>();
var client = new ConsulClient((c) =>
{
c.Address = new System.Uri(consulAddress);
c.WaitTime = new TimeSpan(0, 0, 100);
c.Token = "";
});
startWatchService(client, "SomeServiceName", queue, cancelSrc.Token);
Task.Run(() =>
{
try
{
while (!cancelSrc.IsCancellationRequested)
{
var objs = queue.Receive(cancelSrc.Token);
}
}
catch (OperationCanceledException)
{
return;
}
catch (Exception e)
{
Console.Write($"{e.ToString()}");
}
});
Task.Delay(100000000).Wait();
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Consul" Version="0.7.2.6" />
<PackageReference Include="System.Threading.Tasks.Dataflow" Version="4.9.0" />
</ItemGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment