JsonPath 2.1.0 引入了新的缓存 SPI。这允许 API 用户根据自己的需要配置路径缓存。缓存必须在首次访问前配置好,否则会产生 JsonPathException 异常。JsonPath 有两种缓存实现
com.jayway.jsonpath.spi.cache.LRUCache (默认,线程安全)
com.jayway.jsonpath.spi.cache.NOOPCache (无缓存)
如果您想实现自己的缓存,API 也很简单,例如:
CacheProvider.setCache(new Cache() {
// 简单缓存,不是线程安全的
private Map<String, JsonPath> map = new HashMap<String, JsonPath>();
// 从缓存中获取
@Override
public JsonPath get(String key) {
return map.get(key);
}
// 设置值到缓存
@Override
public void put(String key, JsonPath jsonPath) {
map.put(key, jsonPath);
}
});下面是一个完整示例:
package com.hxstrive.json_path;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.spi.cache.Cache;
import com.jayway.jsonpath.spi.cache.CacheProvider;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Jayway JsonPath 示例
* @author hxstrive.com
*/
public class Demo15 {
public static void main(String[] args) {
String json = "{" +
" \"store\": {" +
" \"book\": [" +
" {" +
" \"category\": \"reference\"," +
" \"author\": \"Nigel Rees\"," +
" \"title\": \"Sayings of the Century\"," +
" \"price\": 8.95" +
" }," +
" {" +
" \"category\": \"fiction\"," +
" \"author\": \"Evelyn Waugh\"," +
" \"title\": \"Sword of Honour\"," +
" \"price\": 12.99" +
" }," +
" {" +
" \"category\": \"fiction\"," +
" \"author\": \"Herman Melville\"," +
" \"title\": \"Moby Dick\"," +
" \"isbn\": \"0-553-21311-3\"," +
" \"price\": 8.99" +
" }," +
" {" +
" \"category\": \"fiction\"," +
" \"author\": \"J. R. R. Tolkien\"," +
" \"title\": \"The Lord of the Rings\"," +
" \"isbn\": \"0-395-19395-8\"," +
" \"price\": 22.99" +
" }" +
" ]," +
" \"bicycle\": {" +
" \"color\": \"red\"," +
" \"price\": 19.95" +
" }" +
" }," +
" \"expensive\": 10" +
"}";
// 自定义缓存
CacheProvider.setCache(new Cache() {
private Map<String, JsonPath> map = new ConcurrentHashMap<String, JsonPath>();
@Override
public JsonPath get(String key) {
System.out.println(">> 从缓存获取 key");
return map.get(key);
}
@Override
public void put(String key, JsonPath jsonPath) {
System.out.println("<< " + key + " 放入缓存");
map.put(key, jsonPath);
}
});
String color = JsonPath.read(json, "$.store.bicycle.color");
System.out.println("color=" + color);
color = JsonPath.read(json, "$.store.bicycle.color");
System.out.println("color=" + color);
}
}运行示例,输出如下:
>> 从缓存获取 key << $.store.bicycle.color 放入缓存 color=red >> 从缓存获取 key color=red
从输出可知,首次访问时缓存没有命中,且进行了缓存设置操作,第二次访问时,缓存命中了。