Introduction to Memcached introduction to of installation and configuration

  • 2020-05-12 06:31:45
  • OfStack

Memcached is a high-performance distributed memory object caching system for dynamic Web applications to reduce database load.
It provides dynamic, database-driven web site speed by caching data and objects in memory to reduce the number of database reads.
Memcached is based on hashmap, which stores a key-value pair. Its daemon (daemon) is written in C, but the client can write in any language and communicate with the daemon through the memcached protocol.

Let's see how Memcached is used

1. Preparation
To / / www. ofstack. com softs / 205838. html

Download the windows version of memcached

Download another java_memcached-release.jar

2. Install
Unzip memcached-1.2.5-win32-bin.zip, CMD enter its directory and execute the following command:

c: > memcached.exe -d install
c: > memcached.exe-l 127.0.0.1-m 32-d start line 1 is to install memcached as a service so that it can work properly, otherwise it will fail!

Line 2 starts memcached, which simply allocates only 32M memory (default 64M), and then listens on the native port and runs for the daemon.

After execution, we can see the memcached.exe process in the task manager.

If you want to install two Memcached on the same Windows machine, see here

Use 3.
Now that the server is up and running, let's write java's client connector.

Unzip java_memcached-release.zip, copy java_memcached-release.jar to the lib directory of the java project,

Then let's write the code. For example, the application class I provided is as follows:


package memcached.test;
import java.util.Date;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
/**
 *  use memcached Cache utility classes .
 */
public class MemCached {
  //  Create a global only 1 The instance 
  protected static MemCachedClient mcc = new MemCachedClient();
  protected static MemCached memCached = new MemCached();
  //  Set up the connection pool with the cache server 
  static {
    //  List of servers and their weights 
    String[] servers = { "127.0.0.1:11211" };
    Integer[] weights = { 3 };
    //  To obtain socke The instance object of the connection pool 
    //  This class is used to create the management client and server communication connection pool, 
    //  The main work of the client (including data communication, server location, hash Code generation, etc.) is done by this class. 
    SockIOPool pool = SockIOPool.getInstance();
    //  Set server information 
    pool.setServers(servers);
    
    //  Set up the Server The weight 
    pool.setWeights(weights);
    //  Sets the initial number of connections, the minimum and maximum number of connections, and the maximum processing time 
    pool.setInitConn(5);
    pool.setMinConn(5);
    pool.setMaxConn(250);
    pool.setMaxIdle(1000 * 60 * 60 * 6);
    //  Set the sleep time for the main thread 
    pool.setMaintSleep(30);
    //  Set the connection heartbeat monitor switch 
    // true: Every communication shall be monitored to see whether the connection is effective, which will double the communication times and increase the network load. 
    //  So in the HighAvailability The more demanding occasion should be set as true
    //  The default is false , it is recommended to keep the default. 
    pool.setAliveCheck(false);
    //  Set the connection failure recovery switch 
    //  Set to true , when the down server is started or the network connection is interrupted socket The connection can also continue to be used, otherwise it will no longer be used .
    //  The default is true , it is recommended to keep the default. 
    pool.setFailback(true);
    //  Set the fault-tolerant switch 
    // true: When the current socket When unavailable, the program will automatically find the available connection and return, otherwise return NULL
    //  The default is true , it is recommended to keep the default. 
    pool.setFailover(true);
    //  Set up the hash algorithm 
    // alg=0  use String.hashCode() To obtain hash code, This method relies on JDK , may not be compatible with other clients, it is recommended not to use 
    // alg=1  use original  Compatible with hash Algorithm, compatible with other clients 
    // alg=2  use CRC32 Compatible with hash Algorithm, compatible with other clients, better performance original algorithm 
    // alg=3  use MD5 hash algorithm 
    //  Before using 3 Kind of hash Algorithm time, look up cache The server USES the remainder method. Use the last 1 Kind of hash Algorithm to find cache Service time use consistent Methods. 
    //  The default value is 0
    pool.setHashingAlg(0);
    //  Set whether to use Nagle Algorithm, because our communication data volume is usually relatively large (relative TCP Control data) and require timely response, 
    //  So this value needs to be set to false (the default is true ) 
    pool.setNagle(false);
    
    //  Set up the socket Read wait timeout value of 
    pool.setSocketTO(3000);
    
    //  Set up the socket The connection waits for a timeout value 
    pool.setSocketConnectTO(0);
    //  Initialize the connection pool 
    pool.initialize();
    //  Compress the setting beyond the specified size (in units of K ) will be compressed 
    // mcc.setCompressEnable(true);  //UnsupportedOperation
    // mcc.setCompressThreshold(64 * 1024);
  }
  private MemCached() {
  }
  /**
   *  Get only 1 The instance .
   * singleton
   * @return
   */
  public static MemCached getInstance() {
    return memCached;
  }
  /**
   *  add 1 The specified key value is entered into the cache .
   * 
   * @param key
   * @param value
   * @return
   */
  public boolean add(String key, Object value) {
    return mcc.add(key, value);
  }
  /**
   *  add 1 The specified key value is entered into the cache .
   * 
   * @param key
   * @param value
   * @param expiry  How long before it expires 
   * @return
   */
  public boolean add(String key, Object value, Date expiry) {
    return mcc.add(key, value, expiry);
  }
  
  
  public boolean set(String key, Object value) {
    return mcc.set(key, value);
  }
  public boolean set(String key, Object value, Date expiry) {
    return mcc.set(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);
  }
  
  
  /**
   *  Gets an object based on the specified keyword .
   * 
   * @param key
   * @return
   */
  public Object get(String key) {
    return mcc.get(key);
  }
}
MemCached

Write an Main test:


public static void main(String[] args) {
    MemCached cache = MemCached.getInstance();
    boolean result1 = cache.add("hello", 1234, new Date(1000 * 2));//  Set up the 2 Seconds after expired 
    System.out.println(" The first 1 time add : " + result1);
    System.out.println("Value : " + cache.get("hello"));
    
    boolean result2 =cache.add("hello", 12345, new Date(1000 * 2));// add fail
    System.out.println(" The first 2 time add : " + result2);
    
    boolean result3 =cache.set("hello", 12345, new Date(1000 * 2));// set successes
    System.out.println(" call set : " + result3);
    
    System.out.println("Value : " + cache.get("hello"));

    try {
      Thread.sleep(1000 * 2);
      System.out.println(" already sleep2 The second ....");
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("Value : " + cache.get("hello"));
  }

The implementation results are as follows:


 The first 1 time add : true
Value : 1234
 The first 2 time add : false
 call set : true
Value : 12345
 already sleep2 The second ....
Value : null

Description:

1. The second add failed because "hello", key, already exists.
2. The call to set was successful because set overrides the existing key-value pairs, which is the difference between add and set
3. After setting the expiration date, cache will automatically expire on time

The above example is for the basic data type, for the normal POJO, if you want to store it, for example, let it implement the java.io.Serializable interface.

Since memcached is a distributed cache server, data sharing among multiple servers requires serialization of objects, so this interface must be implemented, otherwise an error will be reported (java.io.NotSerializableException).

Let's try POJO's storage:


package memcached.test;
public class Person implements java.io.Serializable {
  private static final long serialVersionUID = 1L;

  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

Simple POJO object

The Main method is as follows:


public static void main(String[] args) {
    MemCached cache = MemCached.getInstance();

    Person p1 = new Person();
    p1.setName("Jack");
    cache.add("bean", p1);
    
    Person p2 = (Person) cache.get("bean");
    System.out.println("name=" + p2.getName());//Jack
    p2.setName("Rose");
    
    // cache.replace("bean", p2);
    Person p3 = (Person) cache.get("bean");
    System.out.println("name=" + p3.getName());
  }

In the above code, we changed the name of the object via p2.setName ("Rose"),

What's going to be printed on the last line?

name=Jack
name=JackWhy?

This is because the object we modified is not an object in the cache, but an instance object that was serialized
So what about the modifications? With replace, just comment out the 1 line you left out.

4. Other
Command parameter description for Memcached
-p < num > Listening port
-l < ip_addr > Connect to the IP address, which is native by default
-d start starts the memcached service
-d restart restarts memcached service
-d stop|shutdown shut down the running memcached service
-d install installs the memcached service
-d uninstall uninstall memcached service
-u < username > In order to < username > Runs as root (only valid when running as root)
-m < num > Maximum memory usage, MB. The default 64 MB
-M returns an error when memory runs out, instead of deleting an item
-c < num > The maximum number of simultaneous connections is 1024 by default
-f < factor > Block size growth factor, default is 1.25
-n < bytes > Minimum allocation space, key+value+flags is 48 by default
-h shows help

Memcached can also add key-value pairs to the console by using the command "telnet 127.0.0.1 11211" to enter the Memcached console.

Then use set, add, replace, get, delete.

More details can be found here

5. Advantages and disadvantages of Memcached

When it comes to the advantages of Memcached, they are, of course, fast, easy to operate and easy to scale

If not, there are two main points:

1. Temporary data (data is only stored in memory)
2. Data can only be read by the specified key, fuzzy query is not supported

6. Safeguard measures in case of discontinuation of Memcached
If there is a high volume of traffic to the database, you need to be prepared in advance to deal with the load when memcached stops.

It would be nice if you could copy the data to another server before you stop memcached. Well, this can be done via repcached.

repcached was developed by the Japanese to implement the copy function of memcached,
It is a single master, single slave scheme, but its master/slave are both read-write and can be synchronized with each other
If master is broken and slave detects a broken connection, it will automatically listen and become master


Related articles: