Simple memcached Java client instance

Source: Internet
Author: User

Http://hi.baidu.com/sunsunsoso/blog/item/b197d6a63193718fd0435814.html

Recently, I have been working on the preliminary design of a project. Considering the system expansion and performance problems in the future, I have also found many solutions, one of them is to use the database cache tool memcached (of course, this tool is not limited to the database cache ). Let's briefly introduce what memcached is.

Memcached is a high-performance, distributed memory object cache system that reduces database loads in dynamic applications and improves access speeds. Developed by danga interactive, memcached improves the access speed of livejournal.com. The number of dynamic page views per second on the LJ is several thousand, and the number of users is 7 million. Memcached greatly reduces the database load and makes it easier to allocate resources for faster access.

Baidu has a lot of things on the internet, almost all of which are similar, and few are based on Java. Only after studying the applications of other languages can we try to do simple operations on java. First, we will explain from memcached that the latest version of memcached is developed and designed in C language. It is said that the old version is developed in Perl language and it is an application software, the server that runs on the server as a cache server needs to write the client to communicate with it in a specific language for data caching and retrieval. We usually install and run memcached on a Web server, and then cache the required data. As far as I know, all data cache settings and access operations are performed, and the replacement operation after the data is updated all needs to be performed by the program, rather than automatically (automatic does not know whether it can be successful, huh, huh ). The following uses memcached as an example.

First to begin! First, install and run the memcachedserver. Decompress memcached-1.2.1-win32.zip, enter its directory, and run the following command:

C:> memcached.exe-D install
C:> memcached.exe-l 127.0.0.1-M 32-d start

The first line is to install memcached as a service so that it can run normally. Otherwise, the operation fails! The first line is to start memcached. As a test, we simply allocate only 32 MB of memory, and then listen to the local port and run it as a daemon. After the execution is complete, we can see the memcached.exe process in the task manager. Now that our server is running properly, let's write the Java Client Connection Program.

We copy the java_memcached-release_1.6.jar file in the directory after java_memcached-release_1.6.zip is decompressed to the lib directory of the Java project, and then we compile the Code, for example, an application class I provide is as follows:

Package utils. cache;

Import java. util. date;

Import com. danga. memcached. memcachedclient;
Import com. danga. memcached. sockiopool;

/**
* Use memcached's cache handler class.
*
* @ Author Iron wood box
*
*/
Public class memcached
{
// Create a globally unique instance
Protected static memcachedclient MCC = new memcachedclient ();

Protected static memcached = new memcached ();

// Set the connection pool with the Cache Server
Static {
// Server list and weight
String [] servers = {"127.0.0.1: 11211 "};
Integer [] weights = {3 };

// Obtain the Instance Object of the socke connection pool
Sockiopool pool = sockiopool. getinstance ();

// Set Server Information
Pool. setservers (servers );
Pool. setweights (weights );

// Set the initial connection count, minimum and maximum connections, and maximum processing time.
Pool. setinitconn (5 );
Pool. setminconn (5 );
Pool. setmaxconn (250 );
Pool. setmaxidle (1000*60*60*6 );

// Set the sleep time of the main thread
Pool. setmaintsleep (30 );

// Set TCP Parameters and connection timeout
Pool. setnagle (false );
Pool. setsocketto (3000 );
Pool. setsocketconnectto (0 );

// Initialize the connection pool
Pool. initialize ();

// Compression settings. Data exceeding the specified size (unit: K) will be compressed.
MCC. setcompressenable (true );
MCC. setcompressthreshold (64*1024 );
}

/**
* Protection constructor methods cannot be instantiated!
*
*/
Protected memcached ()
{

}

/**
* Obtain a unique instance.
* @ Return
*/
Public static memcached getinstance ()
{
Return memcached;
}

/**
* Add a specified value to the cache.
* @ Param key
* @ Param Value
* @ Return
*/
Public Boolean add (string key, object value)
{
Return MCC. Add (Key, value );
}

Public Boolean add (string key, object value, date expiry)
{
Return MCC. Add (Key, value, expiry );
}

Public Boolean Replace (string key, object value)
{
Return MCC. Replace (Key, value );
}

Public Boolean Replace (string key, object value, date expiry)
{
Return MCC. Replace (Key, value, expiry );
}

/**
* Get the object based on the specified keyword.
* @ Param key
* @ Return
*/
Public object get (string key)
{
Return MCC. Get (key );
}

Public static void main (string []
ARGs)
{
Memcached cache = memcached. getinstance ();
Cache. Add ("hello", 234 );
System. Out. Print ("Get value:" + cache. Get ("hello "));
}
}

Then, we can save a variable as operated in the main method, and then retrieve it for viewing. We can see that the add method is called first, and then get is performed, after we run it once, the value 234 has been saved to the memcached cache. After we comment out the red line in the main method, we can see that the value obtained by the get operation is also 234, that is, the data already exists in the cache.

We can operate on basic data. For common pojo, if we want to store the data, for example, let it implement Java. io. serializable interface. Because memcached is a distributed cache server, objects must be serialized for data sharing between multiple servers. Therefore, this interface must be implemented; otherwise, an error will be reported. For example, we write a simple test bean as follows:

Class tbean implements java. Io. serializable
{
Private Static final long serialversionuid = 1945562032261321319l;

Private string name;

Public String getname ()
{
Return name;
}

Public void setname (string name)
{
This. Name = Name;
}
}

Then we add the following lines of code to the main method:

Tbean TB = new tbean ();
TB. setname ("Iron wood box ");
Cache. Add ("Bean", Tb );
Tbean tb1 = (tbean) cache. Get ("Bean ");
System. Out. Print ("name =" + tb1.getname ());
Tb1.setname ("Iron wood box_modified ");
Tb1 = (tbean) cache. Get ("Bean ");
System. Out. Print ("name =" + tb1.getname ());

First, we put an instance of tbean into the cache, and then retrieve it and modify the name. Then we can retrieve this object and then look at its name, it is found that the modified object is not an object in the cache, but an instance object serialized, so we do not have to worry about the unintentional modification to the native class, resulting in invalid cache data ~~ It seems that I think too much. Therefore, this indicates that the object obtained from the cache is a copy of the object to be saved. Modifications to the obtained object cannot actually modify the data in the cache, instead, use the provided replace and other methods for modification.

The above is my little learning and practice on memcached in windows. In the future project development process, I will learn more deeply and apply this cache tool, I also hope to discuss the use of this tool with interested colleagues ~~

Related Article

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.