using Microsoft.Extensions.Logging; using Newtonsoft.Json; using PrintBarCode.Business; using PrintBarCode.Helper; using PrintBarCode.Model; using ServiceStack; using ServiceStack.Messaging; using SlnMesnac.Common; using SlnMesnac.Model.domain; using SlnMesnac.Redis; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PrintBarCode { public class MessageClient { private readonly RedisHandler _redisHandler; private PrintBusiness printBusiness = new PrintBusiness(); private readonly DebugConfig debugConfig = DebugConfig.Instance; public delegate void addLog(string message); public static event addLog? addLogEvent; /// /// 刷新日志信息 /// /// public delegate void PrintMessageToListBox(string msg); public event PrintMessageToListBox? PrintMessageToListBoxEvent; public MessageClient(RedisHandler redisHandler) { _redisHandler = redisHandler; string ip = NetworkHelper.GetFirstLocalIPv4Address(); debugConfig.IP = ip; } public void StartListening() { Console.WriteLine($"启动打印监听服务~~~"); Listening(); // 订阅当前工位的频道 _redisHandler.SubscribeToChannel($"print_{debugConfig.IP}", OnMessageReceivedByWorkId); Console.WriteLine($"订阅工位 ===》print_{debugConfig.IP} 成功"); // 订阅当前工位的频道 // 开始处理队列中的未消费消息 // ProcessMessageQueue(); // _redisHandler.SubscribeToChannel("read_messages", OnMessageReceived); } private async void OnMessageReceivedByWorkId(string channelWork, string messageId) { try { var message = _redisHandler.ConsumeMessageFromWorker(debugConfig.IP); if (!string.IsNullOrEmpty(message)) { Console.WriteLine($"消息: {message}"); } } catch (Exception ex) { Console.WriteLine("处理消息时发生错误"); } } private void Listening() { Task.Run(() => { Thread.Sleep(1000 * 2); while (true) { try { string channelWork = $"print_{debugConfig.IP}"; string jsonString = _redisHandler.ConsumeMessageFromWorker(channelWork); // string jsonString = "{\"template\":\"product\",\"printContent\":\"[{\\\"saleOrderCode\\\":\\\"\\\",\\\"materialName\\\":\\\"多功能自动剥线钳\\\",\\\"qrcode\\\":\\\"20241019112921CP001\\\",\\\"materialSpec\\\":\\\"\\\",\\\"qty\\\":\\\"1\\\",\\\"materialCode\\\":\\\"MES.MC.A00861\\\",\\\"barcode\\\":\\\"20241019112921CP001\\\",\\\"productPlanCode\\\":\\\"20241019111402JL012\\\"}]\"}"; if (!string.IsNullOrEmpty(jsonString)) { var result = JsonParser.ParseJson(jsonString); if (result != null) { foreach (var item in result) { if (item is RawBarCodeInfo rawBarCodeInfo) { addLogEvent?.Invoke(rawBarCodeInfo.ToJson()); printBusiness.PrintRawBarCodeInfo(rawBarCodeInfo); } else if (item is ProductBarCodeInfo productBarCodeInfo) { addLogEvent?.Invoke(productBarCodeInfo.ToJson()); printBusiness.PrintProductBarCodeInfo(productBarCodeInfo); }else if (item is BindBarCodeInfo bindBarCodeInfo) { addLogEvent?.Invoke(bindBarCodeInfo.ToJson()); printBusiness.PrintBindBarCodeInfo(bindBarCodeInfo); } Thread.Sleep(1000); } } } Thread.Sleep(1000 * 1); } catch (Exception ex) { Console.WriteLine("处理消息时发生错误"); } } }); } } }