Simple tutorial on using Memcached in java
This article mainly records some basic usage and simple Monitor of Memcached.
Memcached is used by many large companies as a high-concurrency memory Cached system. Recently, it has been used for projects with Memcached and has accumulated some related experience.
Install
The installation of Memcached is simple. Run the following command in Ubuntu.
The Code is as follows:
Sudo apt-get install memcached
Start
In actual use, memcached needs to adjust the memory size, port number, and other commands, then use the following Command to start the application.
The Code is as follows:
Usr/local/bin/memcached-p 11211-m 64 m-d
-P: Specifies the port number.
-M indicates the memory size.
-D is started as a daemon in the background
If you want to trouble shotting, add-vv.
Test
Test is also very simple. Just install the command on the official website.
The Code is as follows:
Telnet local host 11211
Get and Set.
Use in Java
Because the project is java, we use java as an example to introduce the use of Memcached in Java.
There are many Memcached clients in Java. Here we will introduce spymemcached
Spymemcached is easy to use. In the maven project, we add the following dependencies.
The Code is as follows:
<Dependency>
<GroupId> net. spy </groupId>
<ArtifactId> spymemcached </artifactId>
<Version> 2.9.1 </version>
</Dependency>
In this way, we can operate on Memcached.
The Code is as follows:
Public class Memcached {
Private static MemcachedClient MEMCACHED_CLIENT;
Static {
Try {
MEMCACHED_CLIENT = new MemcachedClient (
AddrUtil. getAddresses ("localhost1: 11211 localhost2: 11211 "));
} Catch (Exception e ){
System. err. println ("Cannot init MEMCACHED Memcached Client ");
}
}
Public static void set (String key, String value, Integer expireTime) throws Exception {
MEMCACHED_CLIENT.set (key, expireTime, value );
}
Public static String get (String key) throws Exception {
Object value = MEMCACHED_CLIENT.get (key );
If (null! = Value)
Return value. toString ();
Return null;
}
}
Monitor
We can use the following simple command to learn the running status of Memcached, and use this extension to implement simple Memcached detection shell.
The Code is as follows:
Watch "echo stats | nc 127.0.0.1 11211"
Conclusion
Memcached is easy to use and has corresponding clients on various platforms.
However, sometimes high concurrency may result in Timeout, leading to the inability to hit the buffer. Further investigation is required for the specific cause.
The authors of Memcahed recently wrote groupcache in the Go language, which deserves attention.