CharArrayToStringConverter.java
1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.aukey.example.converter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import java.io.UnsupportedEncodingException;
/**
* @author: wgf
* @create: 2020-06-10 22:39
* @description: 消息类型转换器
* 如果 spring boot 用的是 2.2.7.RELEASE以上的版本则不需要使用此转换器
**/
public class CharArrayToStringConverter implements MessageConverter {
private String defaultCharset = "utf-8";
@Override
public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
// TODO 不发消息不实现转换
return null;
}
@Override
public Object fromMessage(Message message) throws MessageConversionException {
Object content = null;
MessageProperties properties = message.getMessageProperties();
if (properties != null) {
String contentType = properties.getContentType();
if (StringUtils.isBlank(contentType) || contentType.startsWith("text")) {
String encoding = properties.getContentEncoding();
if (encoding == null) {
encoding = this.defaultCharset;
}
try {
content = new String(message.getBody(), encoding);
} catch (UnsupportedEncodingException e) {
throw new MessageConversionException(
"failed to convert text-based Message content", e);
}
}
} else {
content = message.getBody();
}
return content;
}
}