Skip to content

Commit 5794560

Browse files
thachlptishun
andauthored
reuse-objectmapper-defaultjsonparser (#3372)
* reuse-objectmapper-defaultjsonparser Refactor DefaultJsonParser to use a single static ObjectMapper instance instead of creating new instances for each method call, improving performance and memory usage. * Allow injection of custom ObjectMapper in DefaultJsonParser * Add JavaDoc --------- Co-authored-by: Tihomir Mateev <[email protected]>
1 parent b789b62 commit 5794560

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

src/main/java/io/lettuce/core/json/DefaultJsonParser.java

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,27 @@
2525
*/
2626
public class DefaultJsonParser implements JsonParser {
2727

28+
private final ObjectMapper objectMapper;
29+
30+
/**
31+
* Create a new instance of the {@link DefaultJsonParser} initialing a {@link ObjectMapper} with defaults.
32+
*/
33+
public DefaultJsonParser() {
34+
objectMapper = new ObjectMapper();
35+
}
36+
37+
/**
38+
* Create a new instance of the {@link DefaultJsonParser} using the provided {@link ObjectMapper}.
39+
*
40+
* @param objectMapper the {@link ObjectMapper} to use
41+
*/
42+
public DefaultJsonParser(ObjectMapper objectMapper) {
43+
if (objectMapper == null) {
44+
throw new IllegalArgumentException("ObjectMapper must not be null");
45+
}
46+
this.objectMapper = objectMapper;
47+
}
48+
2849
@Override
2950
public JsonValue loadJsonValue(ByteBuffer bytes) {
3051
return new UnproccessedJsonValue(bytes, this);
@@ -52,7 +73,6 @@ public JsonArray createJsonArray() {
5273

5374
@Override
5475
public JsonValue fromObject(Object object) {
55-
ObjectMapper objectMapper = new ObjectMapper();
5676
try {
5777
JsonNode root = objectMapper.valueToTree(object);
5878
return DelegateJsonValue.wrap(root);
@@ -66,9 +86,8 @@ private JsonValue parse(String value) {
6686
return DelegateJsonValue.wrap(NullNode.getInstance());
6787
}
6888

69-
ObjectMapper mapper = new ObjectMapper();
7089
try {
71-
JsonNode root = mapper.readTree(value);
90+
JsonNode root = objectMapper.readTree(value);
7291
return DelegateJsonValue.wrap(root);
7392
} catch (JsonProcessingException e) {
7493
throw new RedisJsonException(
@@ -81,11 +100,10 @@ private JsonValue parse(ByteBuffer byteBuffer) {
81100
return DelegateJsonValue.wrap(NullNode.getInstance());
82101
}
83102

84-
ObjectMapper mapper = new ObjectMapper();
85103
try {
86104
byte[] bytes = new byte[byteBuffer.remaining()];
87105
byteBuffer.get(bytes);
88-
JsonNode root = mapper.readTree(bytes);
106+
JsonNode root = objectMapper.readTree(bytes);
89107
return DelegateJsonValue.wrap(root);
90108
} catch (IOException e) {
91109
throw new RedisJsonException("Failed to process the provided value as JSON", e);

0 commit comments

Comments
 (0)