In the previous part -1 I just show what Jcache looks like, however in reality an enterprise application is built in multi-layers with recurrent access to database that consume many resources and delay the response time.
So what I want to present in this article is how to use Jcache as a separation between the service layer and the database access layer that means that in every read/write operation we can store, read or update objects in the cache.
Prerequisites.
To execute the code in this article you need
- MySQL database, I user MySQL 5.5
- Apache Tomcat 7.
- MySQL connector for java – mysql-connector-java-5.1.9-bin.jar
- Java Temporary caching API.
In Action
I create a servlet as controller , a model and DAO classes to manage the interaction with the application and the database.
The code is organized like the following:
First, initialize and configure the cache:
UserDao.initConnection();
if(this.cache == null){
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();
MutableConfiguration<Integer, User> configuration = new MutableConfiguration<Integer, User>()
.setTypes(Integer.class, User.class)
.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(Duration.ONE_MINUTE))
.setStatisticsEnabled(true);
if(manager.getCache("cache")==null)
this.cache = manager.createCache("cache", configuration);
}
I make this code in the public void init(ServletConfig config) of the servelet, then I create two classes User class and UserDao class. (for the complete code please refer to the code source section).
I use the protected void doGet(HttpServletRequest request, HttpServletResponse response) to read/write values from database if not available in the cache.
// Write in DB & cache
String action = (String)request.getAttribute("action");
if(action != null && action.equals("w")){
for(int i=0;i<100;i++){
User user = new User();
user.setFirstname(UUID.randomUUID().toString());
user.setLastname(UUID.randomUUID().toString());
user = UserDao.save(user);
if(user != null)
cache.put(user.getId(), user);
}
}
// reading operation
PrintWriter pw= response.getWriter();
for(int i=0;i<100;i++){
User user = cache.get(i);
if(user==null){
pw.write("load from database\n");
user = UserDao.load(i);
if(user != null){
cache.put(user.getId(), user);
pw.write(user.getFirstname()+"\n");
}
}else{
pw.write("load from cache\n");
pw.write(user.getFirstname()+"\n");
}
}
Let me explain what happen in the previous code. If the action attribute is not null and equal to “w”, so write values in the database and cache, you notice her that in every request, two operations are required and must made by the developer: writing in the database and the cache, in a next tutorial we can evolve this code to use the read-through and write-through available in the Jcache API.
Then the application retrieve values from the cache, User user = cache.get(i);
if not exist, load it from the database and put it in the cache.