Building a database front-end caching framework using memcached, Spring AOP

Source: Internet
Author: User
Tags aop memcached object object log4j

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
  1. <memcached>
  2. <!--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; -
  3. <client name= "Mclient_0" compressenable= "true" defaultencoding= "UTF-8"
  4. Socketpool= "Pool_0" >
  5. <!--optional to handle errors--
  6. <errorhandler>com.alisoft.xplatform.asf.cache.memcached.memcachederrorhandler
  7. </errorHandler>
  8. </client>
  9. <!--
  10. The Name property is associated with the Socketpool property in the client configuration.
  11. 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.
  12. The Socketto property is the socket operation timeout configuration, in unit Ms. Alivecheck
  13. property indicates whether the socket state is checked before using the socket.
  14. -
  15. <socketpool name= "Pool_0" maintsleep= "socketto=" 3000 "
  16. Failover= "true" alivecheck= "true" initconn= "5" minconn= "5" maxconn= "250"
  17. Nagle= "false" >
  18. <!--set the Memcache server instance address. Multiple addresses with "," separated--
  19. <servers>127.0.0.1:11211</servers>
  20. <!--
  21. Optional configuration. Indicates the load weight of the server instance set above. For example, <weights>3,7</weights> indicates that 30% load is
  22. 10.2.224.36:33001, 70% load in 10.2.224.46:33001
  23. <weights>3,7</weights>
  24. -
  25. </socketpool>
  26. </memcached>


Iv. Creating a memcached client program

Client Tool Classes:

[Java]View Plaincopy
  1. Package com.hl.usersmanager.memcached.client;
  2. Import Com.alisoft.xplatform.asf.cache.ICacheManager;
  3. Import Com.alisoft.xplatform.asf.cache.IMemcachedCache;
  4. Import Com.alisoft.xplatform.asf.cache.memcached.CacheUtil;
  5. Import Com.alisoft.xplatform.asf.cache.memcached.MemcachedCacheManager;
  6. public class Memcachedcache {
  7. Private icachemanager<imemcachedcache> Manager;
  8. Private Imemcachedcache Cache;
  9. Public Memcachedcache () {
  10. Manager = Cacheutil.getcachemanager (Imemcachedcache.class,
  11. MemcachedCacheManager.class.getName ());
  12. Manager.setconfigfile ("Memcached.xml");
  13. Manager.setresponsestatinterval (5*1000);
  14. Manager.start ();
  15. Cache = Manager.getcache ("Mclient_0");
  16. }
  17. /**
  18. * Get Cache interface
  19. * @return
  20. */
  21. Public Imemcachedcache GetCache () {
  22. return cache;
  23. }
  24. /**
  25. * Data into the cache
  26. * @param key
  27. * @param Object
  28. */
  29. public void put (String key,object Object) {
  30. Cache.put (Key, object);
  31. }
  32. /**
  33. * Read data from the cache
  34. * @param key
  35. * @return
  36. */
  37. Public Object get (String key) {
  38. return Cache.get (key);
  39. }
  40. }


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
  1. Package Com.hl.usersmanager.service.impl;
  2. Import java.util.List;
  3. Import org.springframework.beans.factory.annotation.Autowired;
  4. Import Org.springframework.stereotype.Service;
  5. Import org.springframework.transaction.annotation.Transactional;
  6. Import Com.hl.usersmanager.dao.IUserMapper;
  7. Import Com.hl.usersmanager.model.Users;
  8. Import Com.hl.usersmanager.service.IUserService;
  9. Using service annotations does not require the bean to be configured in the configuration file
  10. @Service
  11. public class Userserviceimpl implements iuserservice{
  12. @Autowired
  13. Private Iusermapper Usermapper;
  14. @Override
  15. @Transactional
  16. Public Users finduserbyname (String name) {
  17. return Usermapper.finduserbyname (name);
  18. }
  19. ......
  20. }


Finduserbyname primarily implements the ability to query users by user name, and now we use Spring AOP to implement caching:

[Java]View Plaincopy
  1. Package com.hl.usersmanager.aop.service;
  2. Import Org.apache.log4j.Logger;
  3. Import Org.aspectj.lang.ProceedingJoinPoint;
  4. Import Org.aspectj.lang.annotation.Around;
  5. Import Org.aspectj.lang.annotation.Aspect;
  6. Import Org.aspectj.lang.annotation.Pointcut;
  7. Import org.springframework.beans.factory.annotation.Autowired;
  8. Import Com.hl.usersmanager.memcached.client.MemcachedCache;
  9. Import Com.hl.usersmanager.model.Users;
  10. @Aspect
  11. public class Userserviceinterceptor {
  12. public static final Logger log = Logger
  13. . GetLogger (Userserviceinterceptor.class);
  14. To weave the Cache client tool class Memcachedcache in
  15. @Autowired
  16. Private Memcachedcache Memcachedcache;
  17. /*
  18. * Define Pointcunt
  19. */
  20. @Pointcut ("Execution (* com.hl.usersmanager.service.impl.userserviceimpl.* (..))")
  21. public void Apointcut () {
  22. }
  23. /**
  24. * 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
  25. *
  26. * @param call
  27. * @param name
  28. * @return
  29. */
  30. @Around ("Apointcut () &&args (name)")
  31. Public Users Dofinduserbynamearound (Proceedingjoinpoint call, String name) {
  32. Users users = null;
  33. if (Memcachedcache.getcache (). ContainsKey ("finduserbyname_" + name)) {
  34. Users = (users) memcachedcache.get ("finduserbyname_" + name);
  35. Log.debug ("read from Cache! Finduserbyname_ "+ name);
  36. } else {
  37. try {
  38. Users = (users) call.proceed ();
  39. if (users! = null) {
  40. Memcachedcache.put ("finduserbyname_" + Name, users);
  41. Log.debug ("Cache equipment is executed: finduserbyname_" + name);
  42. }
  43. } catch (Throwable e) {
  44. E.printstacktrace ();
  45. }
  46. }
  47. return users;
  48. }
  49. }

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
      1. <!--Memcachedcache Cache--
      2. <bean id= "Memcachedcache" class= "Com.hl.usersmanager.memcached.client.MemcachedCache" ></bean>

Building a database front-end caching framework using memcached, Spring AOP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.