CoreWCF monitor MySQL table, monitor table insert and update,publish diff rows to client.
get-project -all |Install-Package corewcf.nettcp get-project -all |Install-Package corewcf.primitives get-project -all |Install-Package Microsoft.Extensions.Hosting get-project -all |Install-Package System.ServiceModel.NetTcp get-project -all |Install-Package MySql.Data get-project -all |Install-Package Newtonsoft.Json
Database definition
'db', 'CREATE DATABASE `db` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION=\'N\' */'
table definition
't1', 'CREATE TABLE `t1` (\n `Id` bigint NOT NULL AUTO_INCREMENT,\n `name` varchar(1000) COLLATE utf8mb4_general_ci NOT NULL DEFAULT \'\',\n `isbn` varchar(1000) COLLATE utf8mb4_general_ci NOT NULL DEFAULT \'\',\n `author` varchar(1000) COLLATE utf8mb4_general_ci NOT NULL DEFAULT \'\',\n `comment` text COLLATE utf8mb4_general_ci,\n `content` text COLLATE utf8mb4_general_ci,\n `summary` text COLLATE utf8mb4_general_ci,\n `title` varchar(1000) COLLATE utf8mb4_general_ci NOT NULL DEFAULT \'\',\n `topic` varchar(1000) COLLATE utf8mb4_general_ci NOT NULL DEFAULT \'\',\n `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,\n `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`Id`)\n) ENGINE=InnoDB AUTO_INCREMENT=1321 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci'
1.Create ConsoleApplication to host CoreWCF and install above listed packages
2.
//D:\C\WCFServicePushService\PushService.cs using CoreWCF; using CoreWCF.Channels; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System.Timers; using System.Collections.Concurrent; namespace WCFServicePushService { public interface IMessageCallback { [OperationContract(IsOneWay = true)] void OnPushMessage(string msg); } [ServiceContract(CallbackContract = typeof(IMessageCallback))] public interface IPushService { [OperationContract] void Subscribe(); [OperationContract] void UnSubscribe(); } [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)] public class PushService : IPushService { private static readonly ConcurrentDictionary<IMessageCallback, byte> _clients = new ConcurrentDictionary<IMessageCallback, byte>(); private readonly IMessageCallback _callback; public PushService() { _callback = OperationContext.Current.GetCallbackChannel<IMessageCallback>(); } public void Subscribe() { _clients.TryAdd(_callback, 0); Console.WriteLine($"In WCF Service,{DateTime.Now},client subscribe successfully!"); } public void UnSubscribe() { _clients.TryRemove(_callback, out _); Console.WriteLine($"In WCFService,{DateTime.Now},Client unsubscribed subscription"); } public static void BroadcastMsg(string msg) { foreach (var client in _clients.Keys) { try { client.OnPushMessage(msg); } catch (Exception) { _clients.TryRemove(client, out _); } } } } } //D:\C\WCFServicePushService\Book.cs using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace WCFServicePushService { [Table("t1")] public class Book { [Key] [Column("Id")] public long Id { get; set; } [Column("name")] [MaxLength(1000)] public string Name { get; set; } = string.Empty; [Column("isbn")] [MaxLength(1000)] public string Isbn { get; set; } = string.Empty; [Column("author")] [MaxLength(1000)] public string Author { get; set; } = string.Empty; [Column("comment")] public string? Comment { get; set; } [Column("content")] public string? Content { get; set; } [Column("summary")] public string? Summary { get; set; } [Column("title")] [MaxLength(1000)] public string Title { get; set; } = string.Empty; [Column("topic")] [MaxLength(1000)] public string Topic { get; set; } = string.Empty; [Column("create_time")] public DateTime CreateTime { get; set; } [Column("update_time")] public DateTime UpdateTime { get; set; } public override string ToString() { return $"Id:{Id},Name:{Name},ISBN:{Isbn},Author:{Author},Comment:{Comment},Content:{Content}," + $"Summary:{Summary},Title:{Title},Topic:{Topic},CreateTime:{CreateTime},UpdateTime:{UpdateTime}"; } } } //D:\C\WCFServicePushService\MySqlJHelper.cs using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Data; using System.Security.Cryptography; using System.Text; namespace WCFServicePushService { public class MySqlJHelper { private const string ConnectionString = "server=127.0.0.1;port=3306;user=username;password=passwordvalue;database=db;charset=utf8mb4;"; private Dictionary<long, string> _lastSnapshot = new(); public MySqlConnection GetMySqlConnection() { var conn = new MySqlConnection(ConnectionString); return conn; } public async Task<List<Book>> GetAllT1Rows() { var list = new List<Book>(); const string sql = @"SELECT Id,name,isbn,author,comment,content,summary,title,topic,create_time,update_time FROM t1 ORDER BY Id ASC"; using var conn = GetMySqlConnection(); await conn.OpenAsync(); using var cmd = new MySqlCommand(sql, conn); using var reader = await cmd.ExecuteReaderAsync(); while (await reader.ReadAsync()) { var item = new Book { Id = reader.GetInt64("Id"), Name = reader.GetString("name"), Isbn = reader.GetString("isbn"), Author = reader.GetString("author"), Comment = reader.IsDBNull("comment") ? null : reader.GetString("comment"), Content = reader.IsDBNull("content") ? null : reader.GetString("content"), Summary = reader.IsDBNull("summary") ? null : reader.GetString("summary"), Title = reader.GetString("title"), Topic = reader.GetString("topic"), CreateTime = reader.GetDateTime("create_time"), UpdateTime = reader.GetDateTime("update_time") }; list.Add(item); } return list; } public string ComputeBookMd5(Book book) { var sb = new StringBuilder(); sb.Append(book.Id); sb.Append(book.Name); sb.Append(book.Isbn); sb.Append(book.Author); sb.Append(book.Comment); sb.Append(book.Content); sb.Append(book.Summary); sb.Append(book.Title); sb.Append(book.Topic); sb.Append(book.CreateTime); sb.Append(book.UpdateTime); var bytes = Encoding.UTF8.GetBytes(sb.ToString()); using var md5 = MD5.Create(); var hash = md5.ComputeHash(bytes); return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); } public async Task<List<Book>> CheckTableDiff() { var currentList = await GetAllT1Rows(); var currentDict = currentList.ToDictionary(k => k.Id, v => ComputeBookMd5(v)); var diffBooks = new List<Book>(); foreach (var kv in currentDict) { if (!_lastSnapshot.ContainsKey(kv.Key)) { diffBooks.Add(currentList.First(x => x.Id == kv.Key)); } else { if (_lastSnapshot[kv.Key] != kv.Value) { diffBooks.Add(currentList.First(x => x.Id == kv.Key)); } } } _lastSnapshot = currentDict; return diffBooks; } public async Task InsertTableT1DataAsync(long id) { var guid = Guid.NewGuid(); string name = $"Name_{id}"; string isbn = $"ISBN_{id}_{guid:N}"; string author = $"Author_{id}"; string comment = $"Comment_{id}"; string content = $"Content_{id}"; string summary = $"Summary_{id}"; string title = $"Title_{id}"; string topic = $"Topic_{id}"; const string sql = @" INSERT INTO t1(Id, name, isbn, author, comment, content, summary, title, topic) VALUES(@Id, @name, @isbn, @author, @comment, @content, @summary, @title, @topic) "; using var conn = GetMySqlConnection(); await conn.OpenAsync(); try { using var cmd = new MySqlCommand(sql, conn); cmd.Parameters.AddWithValue("@Id", id); cmd.Parameters.AddWithValue("@name", name); cmd.Parameters.AddWithValue("@isbn", isbn); cmd.Parameters.AddWithValue("@author", author); cmd.Parameters.AddWithValue("@comment", comment); cmd.Parameters.AddWithValue("@content", content); cmd.Parameters.AddWithValue("@summary", summary); cmd.Parameters.AddWithValue("@title", title); cmd.Parameters.AddWithValue("@topic", topic); await cmd.ExecuteNonQueryAsync(); } catch (Exception ex) { Console.WriteLine($"Insert table failed,{ex.Message}"); } finally { } } public async Task<long> GetMaxId() { const string sql = "SELECT MAX(Id) FROM t1"; using var conn = GetMySqlConnection(); await conn.OpenAsync(); using var cmd = new MySqlCommand(sql, conn); var obj = await cmd.ExecuteScalarAsync(); if (obj == DBNull.Value) { return 0; } return Convert.ToInt64(obj); } public async Task<List<Book>> GetDiffBookList() { var currentList = await GetAllT1Rows(); var currentDict = currentList.ToDictionary(k => k.Id, v => ComputeBookMd5(v)); var diffBooks = new List<Book>(); foreach (var kv in currentDict) { if (!_lastSnapshot.ContainsKey(kv.Key)) { diffBooks.Add(currentList.First(x => x.Id == kv.Key)); } else { if (_lastSnapshot[kv.Key] != kv.Value) { diffBooks.Add(currentList.First(x => x.Id == kv.Key)); } } } _lastSnapshot = currentDict; return diffBooks; } public async Task MonitorAndPushDiffAsync() { var diffList = await GetDiffBookList(); if (diffList!=null && diffList.Any()) { string json = Newtonsoft.Json.JsonConvert.SerializeObject(diffList); PushService.BroadcastMsg(json); } } } } //D:\C\WCFServicePushService\Program.cs using CoreWCF; using CoreWCF.Channels; using Microsoft.AspNetCore.Builder; using CoreWCF.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System.Timers; using Microsoft.AspNetCore.Hosting; using MySql.Data.MySqlClient; namespace WCFServicePushService { internal class Program { static long id = 0; static readonly System.Timers.Timer insertTimer = new System.Timers.Timer(); static readonly System.Timers.Timer monitorTimer = new (); private static bool md5MonitorRunning = false; private static readonly MySqlJHelper dbHelper = new MySqlJHelper(); private static bool isRunning = false; static async Task Main(string[] args) { id = await dbHelper.GetMaxId(); insertTimer.Interval = 2000; insertTimer.Elapsed += InsertTimer_Elapsed1; insertTimer.Start(); monitorTimer.Interval = 10000; monitorTimer.Elapsed += MonitorTimer_Elapsed; monitorTimer.Start(); //await WCFServicePushDemoAsync(args); var builder = WebApplication.CreateBuilder(args); builder.Services.AddServiceModelServices(); builder.WebHost.UseNetTcp(8000); var app = builder.Build(); app.UseServiceModel(serviceBuilder => { var binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; binding.MaxReceivedMessageSize = int.MaxValue; serviceBuilder.AddService<PushService>() .AddServiceEndpoint<PushService, IPushService>(binding, "/PushService"); }); try { Console.WriteLine("Listening net.tcp://127.0.0.1:8000/PushService"); await app.RunAsync(); } finally { insertTimer.Stop(); insertTimer.Dispose(); monitorTimer.Stop(); monitorTimer.Dispose(); } Console.ReadLine(); } private static async void MonitorTimer_Elapsed(object? sender, ElapsedEventArgs e) { if (md5MonitorRunning) { return; } md5MonitorRunning = true; try { await dbHelper.MonitorAndPushDiffAsync(); } catch (Exception ex) { Console.WriteLine($"Md5 Monitor error:{ex.Message}"); } finally { md5MonitorRunning = false; } } private static async void InsertTimer_Elapsed1(object? sender, ElapsedEventArgs e) { if(isRunning) { Console.WriteLine($"In WCF Service,{DateTime.Now} inserting not finished,skip this time."); return; } isRunning = true; try { long newId = Interlocked.Increment(ref id); await dbHelper.InsertTableT1DataAsync(newId); } catch (Exception ex) { Console.WriteLine($"Timer exception:{ex?.Message}"); } finally { isRunning = false; } } static async Task WCFServicePushDemoAsync(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Services.AddServiceModelServices(); builder.WebHost.UseNetTcp(8000); var app = builder.Build(); app.UseServiceModel(serviceBuilder => { var binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; binding.MaxReceivedMessageSize = int.MaxValue; serviceBuilder.AddService<PushService>() .AddServiceEndpoint<PushService, IPushService>(binding, "/PushService"); }); var timer = new System.Timers.Timer(2000); timer.Elapsed += (s, e) => { //var msg = $"{DateTime.Now},WCF service push msg:{DateTime.Now}_Id_{Interlocked.Add(ref id, 1)}_{Guid.NewGuid():N}"; //PushService.BroadcastMsg(msg); //Console.WriteLine($"In WCF Service,push msg:\n{msg}\n\n"); }; timer.Start(); Console.WriteLine($"In CoreWCF NetTcp Servive started :net.tcp://127.0.0.1:8000/PushService"); try { Console.WriteLine("Listening net.tcp://127.0.0.1:8000/PushService"); await app.RunAsync(); } finally { timer.Stop(); timer.Dispose(); } } } }
3.Create another console as Consumer application,
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net10.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <PackageReference Include="newtonsoft.json" Version="13.0.4" /> <PackageReference Include="System.ServiceModel.NetTcp" version="10.1.0" /> </ItemGroup> </Project>
4.
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.ServiceModel; namespace ConsoleApp1 { internal class Program { static void Main(string[] args) { SubWCFService(); Console.ReadLine(); } static void SubWCFService() { var callbackObj = new ClientCallback(); var instanceCtx = new InstanceContext(callbackObj); var binding = new NetTcpBinding(SecurityMode.None) { MaxReceivedMessageSize = int.MaxValue, OpenTimeout = TimeSpan.FromSeconds(30), SendTimeout = TimeSpan.FromMinutes(10), ReceiveTimeout = TimeSpan.FromMinutes(10), CloseTimeout = TimeSpan.FromSeconds(30) }; binding.ReliableSession.Enabled = false; var address = new EndpointAddress("net.tcp://127.0.0.1:8000/PushService"); var factory = new DuplexChannelFactory<IPushService>( instanceCtx, binding, address); var proxy = factory.CreateChannel(); proxy.Subscribe(); Console.WriteLine("Subscribed. Press Enter to exit..."); Console.ReadLine(); ((IClientChannel)proxy).Close(); factory.Close(); } } public interface IMessageCallback { [OperationContract(IsOneWay = true)] void OnPushMessage(string msg); } [ServiceContract(CallbackContract = typeof(IMessageCallback))] public interface IPushService { [OperationContract] void Subscribe(); [OperationContract] void UnSubscribe(); } public class ClientCallback : IMessageCallback { public void OnPushMessage(string msg) { var diffBooks = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Book>>(msg); Console.WriteLine($"In client,{DateTime.Now},there are {diffBooks.Count} different items:\n"); foreach (var b in diffBooks) { Console.WriteLine($"{b.ToString()}"); } Console.WriteLine("\n\n\n\n\n"); } } [Table("t1")] public class Book { [Key] [Column("Id")] public long Id { get; set; } [Column("name")] [MaxLength(1000)] public string Name { get; set; } = string.Empty; [Column("isbn")] [MaxLength(1000)] public string Isbn { get; set; } = string.Empty; [Column("author")] [MaxLength(1000)] public string Author { get; set; } = string.Empty; [Column("comment")] public string? Comment { get; set; } [Column("content")] public string? Content { get; set; } [Column("summary")] public string? Summary { get; set; } [Column("title")] [MaxLength(1000)] public string Title { get; set; } = string.Empty; [Column("topic")] [MaxLength(1000)] public string Topic { get; set; } = string.Empty; [Column("create_time")] public DateTime CreateTime { get; set; } [Column("update_time")] public DateTime UpdateTime { get; set; } public override string ToString() { return $"Id:{Id},Name:{Name},ISBN:{Isbn},Author:{Author},Comment:{Comment},Content:{Content}," + $"Summary:{Summary},Title:{Title},Topic:{Topic},CreateTime:{CreateTime},UpdateTime:{UpdateTime}"; } } }
5.Start service,then consumer







浙公网安备 33010602011771号