using MSCRM_Utility;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using Confluent.Kafka;
using static Confluent.Kafka.ConfigPropertyNames;
namespace Crm.App.WebApi.Common
{
public class KafkaHelper
{
private static string NameServerAddress = ConfigurationManager.AppSettings["NameServerAddress_Kafka"];
private static string Topic = ConfigurationManager.AppSettings["Topic"];
private static string UserName = ConfigurationManager.AppSettings["UserName_Kafka"];
private static string Password = ConfigurationManager.AppSettings["Password_Kafka"];
private static CrmUtil crmUtil = new CrmUtil();
private static IProducer<string, object> producer;
/// <summary>
/// 发送消息
/// </summary>
/// <param name="body"></param>
/// <param name="topic"></param>
public static void Publish(string body, string topic = null)
{
if (producer == null)
{
Dictionary<string, string> config = new Dictionary<string, string>();
config.Add("bootstrap.servers", NameServerAddress);
config.Add("api.version.request", "true");
config.Add("security.protocol", "SASL_PLAINTEXT");
config.Add("sasl.mechanisms", "SCRAM-SHA-256");
config.Add("sasl.kerberos.service.name", "kafka");
config.Add("debug", "security,broker,protocol");
config.Add("sasl.username", UserName);
config.Add("sasl.password", Password);
var builder = new ProducerBuilder<string, object>(config);
builder.SetValueSerializer(new KafkaConverter());//设置序列化方式
producer = builder.Build();
}
JObject entityKey = JsonConvert.DeserializeObject<JObject>(body);
string Key = Guid.NewGuid().ToString();
if (entityKey != null && entityKey["entityId"] != null && !string.IsNullOrEmpty(entityKey["entityId"].ToString()))
{
Key = entityKey["entityId"].ToString();
}
if (string.IsNullOrWhiteSpace(topic))
{
producer.Produce(Topic, new Message<string, object> { Key = Key, Value = body }, DeliveryHandler);
}
else
{
producer.Produce(topic, new Message<string, object> { Key = Key, Value = body }, DeliveryHandler);
}
//producer.Dispose();
//producer.Flush(TimeSpan.FromSeconds(1));
}
/// <summary>
/// 发送消息后的回调函数
/// </summary>
/// <param name="obj"></param>
private static void DeliveryHandler(DeliveryReport<string, object> obj)
{
Error error = obj.Error;
if (Controllers.MQController.WriteLog)
{
if (error != null)
{
crmUtil.WriteLog("MQ_Result", JsonConvert.SerializeObject(obj));
}
}
}
public class KafkaConverter : ISerializer<object>
{
/// <summary>
/// 序列化数据成字节
/// </summary>
/// <param name="data"></param>
/// <param name="context"></param>
/// <returns></returns>
public byte[] Serialize(object data, SerializationContext context)
{
var json = JsonConvert.SerializeObject(data);
return Encoding.UTF8.GetBytes(json);
}
}
}
}