【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
使用C#发送消息,spring boot rabbitmq可订阅
要实现以上功能,需要解决三个问题
1.序列化之后时间格式不一致
2.命名规则不同(java首字母小写)
3.spring boot rabbitmq需要typeid及content_type等
解决前两个问题比较容易,序列化的时候设置
private static readonly JsonSerializerSettings settings = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
DateFormatString = "yyy-MM-ddThh:mm:ss.fff",
// 设置为驼峰命名
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
解决最后一个问题就需要麻烦一点,就需要把properties里所需要的属性及头都要设置上
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#发送的消息了
来源:oschina
链接:https://my.oschina.net/u/1865350/blog/3001343