Skip to content

QueryCache

Yong Zhu edited this page May 7, 2020 · 3 revisions

jSqlBox comes with a query cache SimpleCacheHandler, which is an implementation of the SqlHandler interceptor. It only works for the query method. First query will read from database, and subsequent queries will be read from the cache. Use the SimpleCacheHandler query cache, usually configured as a singleton or global variable, passed as a parameter in the various query methods of the pintea series methods:

SimpleCacheHandler simpleCache=new SimpleCacheHandler();
/ / First query from database
pQuery(simpleCache, new EntityListHandler(), DemoUser.class, "select * from DemoUser where age>?", 0);
/ / The second time will read from the cache, if the SQL and parameters are same.
pQuery(simpleCache, new EntityListHandler(), DemoUser.class, "select * from DemoUser where age>?", 0);

The above test code is located in the unit test SqlHandlersTest.java.

jSqlBox's default SimpleCacheHandler is a simple LRU cache, using the LinkedHashMap table in memory to cache SQL query results. When the cache is full of data, it will clear the data that has not been accessed for the longest time. SimpleCacheHandler has two construction methods:

SimpleCacheHandler()
SimpleCacheHandler(int capacity, int aliveSeconds)

The latter configuration allows setting the cache size and cache expiration time. The cache expiration time is in seconds (the internal value is adjusted to the nearest value to 1, 10, 100, 1000, 10000...). If the first type of no-argument constructor is used, the default cache size is 500 query records and 1000 seconds of cache invalidation time.

Another way to use the SimpleCacheHandler to query the cache is to set the cache interceptor SimpleCacheHandler to a global interceptor when the SqlBoxContext is constructed (see the jSqlBox configuration section), such as:

DbContext ctx=new DbContext(ds, config);
ctx.setHandlers(new SimpleCacheHandler());

This way, you don't have to manually add the cache interceptor in the query method every time, but because the cache may cause the existence of dirty data, this method usually should not participate in the transaction operation. You can consider creating a SqlBoxContext with a cache configured separately. Assign a dedicated data source for query purposes only.

jSqlBox's own query caching mechanism is relatively simple. Like MyBatis, it is coarse-grained, not for rowsets. The cached primary key uses "time + SQL + parameters", as long as the SQL spelling or parameter values ​​are any different. jSqlBox thinks that this is two different queries, so which queries need to use the cache need to be carefully considered, queries whose parameters change frequently should not use the cache.

If you want to write your own cache class, you can refer to the "Handler class introduction" section and the source code of the SimpleCacheHandler class.