使用C#發送消息,spring boot rabbitmq可訂閱java
要實現以上功能,須要解決三個問題spring
1.序列化以後時間格式不一致json
2.命名規則不一樣(java首字母小寫)app
3.spring boot rabbitmq須要typeid及content_type等oop
解決前兩個問題比較容易,序列化的時候設置code
private static readonly JsonSerializerSettings settings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, DateFormatString = "yyy-MM-ddThh:mm:ss.fff", // 設置爲駝峯命名 ContractResolver = new CamelCasePropertyNamesContractResolver() };
解決最後一個問題就須要麻煩一點,就須要把properties裏所須要的屬性及頭都要設置上orm
var properties = channel.CreateBasicProperties(); properties.DeliveryMode = 2; properties.ContentEncoding = "UTF-8"; properties.ContentType = "application/json"; properties.Priority = 0; Dictionary<string, object> headers = new Dictionary<string, object>(); properties.Headers = headers; // body value string jsonContent = JsonConvert.SerializeObject(entity, settings); if (!string.IsNullOrEmpty(javaClass)) { properties.Headers.Add("__TypeId__", javaClass); } else { //再次轉義 jsonContent = JsonConvert.SerializeObject(jsonContent); properties.Headers.Add("__TypeId__", "java.lang.String"); } var body = Encoding.UTF8.GetBytes(jsonContent);
這樣spring boot rabbitmq就能夠處理C#發送的消息了rabbitmq