|
| 1 | +using Common.Logging; |
| 2 | +using IntegrationEngine.Core.Jobs; |
| 3 | +using IntegrationEngine.Core.Mail; |
| 4 | +using IntegrationEngine.Core.Storage; |
| 5 | +using Nest; |
| 6 | +using System; |
| 7 | +using System.Collections.Generic; |
| 8 | +using System.Linq; |
| 9 | +using System.Messaging; |
| 10 | +using System.Text; |
| 11 | +using MSMessageQueue = System.Messaging.MessageQueue; |
| 12 | + |
| 13 | +namespace IntegrationEngine.MessageQueue |
| 14 | +{ |
| 15 | + public class MsmqListener : IMessageQueueListener |
| 16 | + { |
| 17 | + public IList<Type> IntegrationJobTypes { get; set; } |
| 18 | + public ILog Log { get; set; } |
| 19 | + public IMailClient MailClient { get; set; } |
| 20 | + public IntegrationEngineContext IntegrationEngineContext { get; set; } |
| 21 | + public IElasticClient ElasticClient { get; set; } |
| 22 | + public MSMessageQueue MSMessageQueue { get; set; } |
| 23 | + string _queueName { get; set; } |
| 24 | + public string QueueName |
| 25 | + { |
| 26 | + get { return _queueName; } |
| 27 | + set |
| 28 | + { |
| 29 | + if (!MSMessageQueue.Exists(QueueName)) |
| 30 | + MSMessageQueue.Create(QueueName); |
| 31 | + _queueName = value; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + public void Listen() |
| 36 | + { |
| 37 | + Message newMessage = MSMessageQueue.Receive(); |
| 38 | + var body = newMessage.Body as byte[]; |
| 39 | + var message = Encoding.UTF8.GetString(body); |
| 40 | + Log.Debug(x => x("Message queue listener received {0}", message)); |
| 41 | + if (IntegrationJobTypes != null && !IntegrationJobTypes.Any()) |
| 42 | + return; |
| 43 | + var type = IntegrationJobTypes.FirstOrDefault(t => t.FullName.Equals(message)); |
| 44 | + var integrationJob = Activator.CreateInstance(type) as IIntegrationJob; |
| 45 | + integrationJob = AutoWireJob(integrationJob, type); |
| 46 | + try |
| 47 | + { |
| 48 | + if (integrationJob != null) |
| 49 | + integrationJob.Run(); |
| 50 | + } |
| 51 | + catch (Exception exception) |
| 52 | + { |
| 53 | + Log.Error(x => x("Integration job did not run successfully ({0})}", message), exception); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + T AutoWireJob<T>(T job, Type type) |
| 58 | + { |
| 59 | + if (type.GetInterface(typeof(IMailJob).Name) != null) |
| 60 | + (job as IMailJob).MailClient = MailClient; |
| 61 | + if (type.GetInterface(typeof(ISqlJob).Name) != null) |
| 62 | + (job as ISqlJob).DbContext = IntegrationEngineContext; |
| 63 | + if (type.GetInterface(typeof(ILogJob).Name) != null) |
| 64 | + (job as ILogJob).Log = Log; |
| 65 | + if (type.GetInterface(typeof(IElasticsearchJob).Name) != null) |
| 66 | + (job as IElasticsearchJob).ElasticClient = ElasticClient; |
| 67 | + return job; |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments