Database access can be a bottleneck for many websites. Connection pool exhaustion, memory overflow, and so on. As already mentioned, if our site is a large distributed site, then using memcached to implement a database's front-end caching is a good choice, but if the site itself is small enough to have only one server, or even the kind of VPS, it is not recommended to use memcached, so Use Hibernate or the MyBatis framework to bring your own cache system on the line.
First, open memcached server-side services
If you have already installed the Memcached server-side program, make sure that the server-side service is turned on.
Ii. introduction of Jar
1. Alisoft-xplatform-asf-cache-2.5.1.jar
2. Commons-logging-1.0.4.jar
3. Hessian-3.0.1.jar
4. Log4j-1.2.9.jar
5. Stax-api-1.0.1.jar
6. Wstx-asl-2.0.2.jar
Iii. Creating a memcached client configuration file
[Java]View Plaincopy
- <memcached>
- <!--The Name property is a unique identifier for using the cache in the program; the Socketpool property will be associated to the Socketpool configuration later; -
- <client name= "Mclient_0" compressenable= "true" defaultencoding= "UTF-8"
- Socketpool= "Pool_0" >
- <!--optional to handle errors--
- <errorhandler>com.alisoft.xplatform.asf.cache.memcached.memcachederrorhandler
- </errorHandler>
- </client>
- <!--
- The Name property is associated with the Socketpool property in the client configuration.
- The Maintsleep property is the check interval for the background thread management Socketio pool, and if set to 0, indicates that no background thread is required to maintain the socketio thread pool, which is managed by default.
- The Socketto property is the socket operation timeout configuration, in unit Ms. Alivecheck
- property indicates whether the socket state is checked before using the socket.
- -
- <socketpool name= "Pool_0" maintsleep= "socketto=" 3000 "
- Failover= "true" alivecheck= "true" initconn= "5" minconn= "5" maxconn= "250"
- Nagle= "false" >
- <!--set the Memcache server instance address. Multiple addresses with "," separated--
- <servers>127.0.0.1:11211</servers>
- <!--
- Optional configuration. Indicates the load weight of the server instance set above. For example, <weights>3,7</weights> indicates that 30% load is
- 10.2.224.36:33001, 70% load in 10.2.224.46:33001
- <weights>3,7</weights>
- -
- </socketpool>
- </memcached>
Iv. Creating a memcached client program
Client Tool Classes:
[Java]View Plaincopy
- Package com.hl.usersmanager.memcached.client;
- Import Com.alisoft.xplatform.asf.cache.ICacheManager;
- Import Com.alisoft.xplatform.asf.cache.IMemcachedCache;
- Import Com.alisoft.xplatform.asf.cache.memcached.CacheUtil;
- Import Com.alisoft.xplatform.asf.cache.memcached.MemcachedCacheManager;
- public class Memcachedcache {
- Private icachemanager<imemcachedcache> Manager;
- Private Imemcachedcache Cache;
- Public Memcachedcache () {
- Manager = Cacheutil.getcachemanager (Imemcachedcache.class,
- MemcachedCacheManager.class.getName ());
- Manager.setconfigfile ("Memcached.xml");
- Manager.setresponsestatinterval (5*1000);
- Manager.start ();
- Cache = Manager.getcache ("Mclient_0");
- }
- /**
- * Get Cache interface
- * @return
- */
- Public Imemcachedcache GetCache () {
- return cache;
- }
- /**
- * Data into the cache
- * @param key
- * @param Object
- */
- public void put (String key,object Object) {
- Cache.put (Key, object);
- }
- /**
- * Read data from the cache
- * @param key
- * @return
- */
- Public Object get (String key) {
- return Cache.get (key);
- }
- }
V. Using spring AOP to implement data caching and reading at the service layer of the data query
The process of implementing data caching is simple, that is, before the service layer queries the database operation to determine whether the data to be queried exists in the cache, if it does not exist in the database query, the query is completed after the data into the cache system, if the data to be queried in the cache already exists, it is read directly from the cache. You do not need to manipulate the database. This greatly reduces the number of connections to the database. The principle is so simple.
However, if the service layer code is directly modified, it violates the "open-closed" principle, it will also cause the operation code of the cache system scattered throughout the service layer, inconvenient code management and maintenance. So, Spring AOP is a gorgeous debut. It uses non-intrusive to create and manage these cache operation codes.
We don't tell you about the knowledge of spring AOP itself. Resources:
As the first to determine whether the query data exists in the cache system, if there is directly read from the cache, that is, the service layer of the query code is not executed at all, on the other hand, if the data does not exist in the cache system, from the database query results, we need to put it into the cache system.
What do we see in some of the equipment for spring AOP? That's the most powerful surround-notice outfit @Around!
The following is an example of userservice with the following source code:
[Java]View Plaincopy
- Package Com.hl.usersmanager.service.impl;
- Import java.util.List;
- Import org.springframework.beans.factory.annotation.Autowired;
- Import Org.springframework.stereotype.Service;
- Import org.springframework.transaction.annotation.Transactional;
- Import Com.hl.usersmanager.dao.IUserMapper;
- Import Com.hl.usersmanager.model.Users;
- Import Com.hl.usersmanager.service.IUserService;
- Using service annotations does not require the bean to be configured in the configuration file
- @Service
- public class Userserviceimpl implements iuserservice{
- @Autowired
- Private Iusermapper Usermapper;
- @Override
- @Transactional
- Public Users finduserbyname (String name) {
- return Usermapper.finduserbyname (name);
- }
- ......
- }
Finduserbyname primarily implements the ability to query users by user name, and now we use Spring AOP to implement caching:
[Java]View Plaincopy
- Package com.hl.usersmanager.aop.service;
- Import Org.apache.log4j.Logger;
- Import Org.aspectj.lang.ProceedingJoinPoint;
- Import Org.aspectj.lang.annotation.Around;
- Import Org.aspectj.lang.annotation.Aspect;
- Import Org.aspectj.lang.annotation.Pointcut;
- Import org.springframework.beans.factory.annotation.Autowired;
- Import Com.hl.usersmanager.memcached.client.MemcachedCache;
- Import Com.hl.usersmanager.model.Users;
- @Aspect
- public class Userserviceinterceptor {
- public static final Logger log = Logger
- . GetLogger (Userserviceinterceptor.class);
- To weave the Cache client tool class Memcachedcache in
- @Autowired
- Private Memcachedcache Memcachedcache;
- /*
- * Define Pointcunt
- */
- @Pointcut ("Execution (* com.hl.usersmanager.service.impl.userserviceimpl.* (..))")
- public void Apointcut () {
- }
- /**
- * Surround equipment to intercept queries if there is data in the cache, read directly from the cache, otherwise read from the database and put the results in the cache
- *
- * @param call
- * @param name
- * @return
- */
- @Around ("Apointcut () &&args (name)")
- Public Users Dofinduserbynamearound (Proceedingjoinpoint call, String name) {
- Users users = null;
- if (Memcachedcache.getcache (). ContainsKey ("finduserbyname_" + name)) {
- Users = (users) memcachedcache.get ("finduserbyname_" + name);
- Log.debug ("read from Cache! Finduserbyname_ "+ name);
- } else {
- try {
- Users = (users) call.proceed ();
- if (users! = null) {
- Memcachedcache.put ("finduserbyname_" + Name, users);
- Log.debug ("Cache equipment is executed: finduserbyname_" + name);
- }
- } catch (Throwable e) {
- E.printstacktrace ();
- }
- }
- return users;
- }
- }
Surround notification equipment requires a parameter of type Proceedingjoinpoint, its strength is that it can proxy a pointcut, specify whether the Pointcut method executes, or get the result after execution!!
Memcachedcache.getcache (). ContainsKey ("finduserbyname_" + name)
You can determine whether there is a specified data in the cache. If any, read directly from the cache:
Users = (users) memcachedcache.get ("finduserbyname_" + name);
Otherwise, call the Pointcut Userserviceimpl's Finduserbyname method:
Users = (users) call.proceed ();
Call.proceed () represents the method that executes the pointcut.
With spring AOP, the entire cache system code looks so elegant! Userserviceimpl do not know what the outside world, more do not know the outside call its finduserbyname time has been intercepted!
You don't need to cache the system that day, just remove the code from the AOP block.
Of course, we also need to register a bean for the Memcached Client tool class in the Spring configuration file:
[Java]View Plaincopy
- <!--Memcachedcache Cache--
- <bean id= "Memcachedcache" class= "Com.hl.usersmanager.memcached.client.MemcachedCache" ></bean>
Building a database front-end caching framework using memcached, Spring AOP