Memcached Introduction to the client of

We already know ,memcached It's a distributed cache system ,memcached The server is just a place to cache data , It's not distributed , and memcached The distributed client is the place to realize .

Memcached It is now widely used , There are also many versions of client implementation , Basically every language has . such as :Memcached client for Java、Spymemcached、xMemcached, Each has its own advantages and disadvantages . because Memcached client for Java yes Memcached The official client , Widely applied , The operation is relatively stable , The new version has also improved in performance . We will use the client to demonstrate the actual combat next .

Memcached Client download

Download address :https://github.com/gwhalin/Memcached-Java-Client/downloads

Memcached The client uses

downloaded Memcached There are four clients jar package , Namely :commons-pool-1.5.6.jar、java_memcached-release_2.6.6.jar、slf4j-api-1.6.1.jar、slf4j-simple-1.6.1.jar. Put these four jar Just add the package to the build path of the project .

Memcached Using examples

We'll take the cache menu list as an example , When accessing the background home page to load the system menu list , First judge whether the menu list exists memcached in , If not, read the system menu list from the data , Coexist to memcached, Otherwise directly from memcached Read from . as follows :

MemcachedFactory.java

public class MemcachedFactory {

// establish MemCachedClient Global object

private static MemCachedClient memCachedClient = new MemCachedClient();

static {

// Create a list of servers and their weights

String[] servers = { "127.0.0.1:11211" };

Integer[] weights = { 3 };

// establish Socket Connection pool

SockIOPool pool = SockIOPool.getInstance();

// Set server information

pool.setServers(servers);

pool.setWeights(weights);

pool.setFailover(true);

// Set the number of initial connections 、 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 main thread sleep time

pool.setMaintSleep(30);

// Set up TCP Parameters 、 Connection timeout, etc

pool.setNagle(false);

pool.setSocketTO(3000);

pool.setSocketConnectTO(0);

pool.setAliveCheck(true);

// Initialize connection pool

pool.initialize();

}

protected MemcachedFactory() {

}

// Memcached example

protected static MemcachedFactory instance = new MemcachedFactory();

public static MemcachedFactory getInstance() {

return instance;

}

/**

* Add cache records

* @param key

* @param value

* @return

*/

public boolean add(String key, Object value) {

return memCachedClient.add(key, value);

}

/**

* Add cache records , Valid for expiry

* @param key

* @param value

* @param expiry

* @return

*/

public boolean add(String key, Object value, Date expiry) {

return memCachedClient.add(key, value, expiry);

}

/**

* Cache query result objects QueryResult

* @param key

* @param value

* @return

*/

public boolean add(String key, QueryResult<Menu> value) {

return memCachedClient.add(key, value);

}

/**

* Extract cache records

* @param key

* @return

*/

public Object get(String key) {

return memCachedClient.get(key);

}

/**

* Determine whether the cache exists

* @param key

* @return

*/

public boolean keyExist(String key) {

return memCachedClient.keyExists(key);

}

}

 

IndexController.java

@Controller

public class IndexCtroller{

@Autowired

private IIndexService indexService;

@RequestMapping(value = "/back/index")

public String index(HttpServletRequest request) {

MemcachedFactory mcInstance = MemcachedFactory.getInstance();

String jsonTree = null;

// non-existent key The cache records query the database and add them to the database memcached

if(!mcInstance.keyExist("jsonTree")) {

List<Menu> menuList = indexService.queryMenu();

List2JsonUtil<Menu> list2JsonUtil = new List2JsonUtil<Menu>(new Menu());

jsonTree = list2JsonUtil.getJosnStrFromList(menuList, null);

mcInstance.add("jsonTree", jsonTree);

// Otherwise directly from memcached Extract from

}else {

jsonTree = (String) mcInstance.get("jsonTree");

}

if(null != jsonTree){

request.setAttribute("jsonTree", jsonTree);

}

return "/back/index";

}

}

Page effects

It takes time to read the menu list from the database for the first time

 

Let's write it down IndexController.java in memcached Take a look at the time it takes to read the menu list from the database for the first time .

 

You can see from the above picture that , It takes time to access the data load menu list for the first time 1.17s, These times include querying records from the database and converting query results to json Time to format data .

First time from memcached It takes time to read the menu list

Let go of IndexController.java in memcached Related code , Take a look at the first time from memcached It takes time to read the menu list .

You can see from the above picture that , When the menu list has been saved memcached In the after , First time from memcached Time consuming to read menu list 21.970ms, There is no need to query records from the database and convert the query results to json Time consuming of formatted data . obviously , From first visit to database and first visit to memcached Look at , The response time is really much faster . stay memcached backstage , We see a list of access menus jsonTree Information about , as follows :

The time taken to read the menu list above may not be very accurate , Due to the influence of browser and other factors , As the frequency of access increases , Access the database and access memcached It's going to take less time , And then fluctuate in a certain range . But one thing is for sure , visit memcached No need to query records from the database and convert the query results to json Time consuming of formatted data , Reduce the frequency of database access and server pressure .

Distributed cache technology memcached Study ( 5、 ... and )—— memcached java More articles about the use of client

  1. Distributed cache technology redis Learning Series

    Distributed cache technology redis Learning Series ( One )--redis Introduction and linux Installation and operation of redis Problem sorting Distributed cache technology redis Learning Series ( Two )-- Explain in detail redis data structure ( Memory model ) And common commands ...

  2. Distributed cache technology redis Learning Series ( One )——redis Introduction and linux The installation of the

    redis brief introduction redis yes NoSQL(No Only SQL, Non relational database ) A kind of ,NoSQL In order to Key-Value In the form of data storage . The current mainstream distributed caching technologies are redis,memcached,ssd ...

  3. Distributed cache technology redis Study ( One )——redis Introduction and linux The installation of the

    redis brief introduction redis yes NoSQL(No Only SQL, Non relational database ) A kind of ,NoSQL In order to Key-Value In the form of data storage . The current mainstream distributed caching technologies are redis,memcached,ssd ...

  4. Distributed cache technology redis Learning Series ( 3、 ... and )——redis Advanced applications ( Master-slave 、 Transactions and locks 、 Persistence )

    Above, < Explain in detail redis data structure ( Memory model ) And common commands > It introduces redis Data types and common commands , Let's study this article redis Some advanced features . Security settings Set the client operation secret redis install ...

  5. Distributed cache technology redis Study ( 3、 ... and )——redis Advanced applications ( Master-slave 、 Transactions and locks 、 Persistence )

    Above, < Explain in detail redis data structure ( Memory model ) And common commands > It introduces redis Data types and common commands , Let's study this article redis Some advanced features . Directory as follows : Security settings Set the client operation secret Customer ...

  6. Distributed cache technology redis Learning Series ( 5、 ... and )——redis actual combat (redis And spring Integrate , Distributed lock implementation )

    This article is about redis Learn the fifth part of the series , Click on the link below to go back to the series <redis Introduction and linux The installation of the > < Explain in detail redis data structure ( Memory model ) And common commands > <redi ...

  7. Distributed cache technology redis Learning Series ( Four )——redis Advanced applications ( Cluster building 、 Cluster partition principle 、 Cluster operation )

    This article is about redis Learn the fourth part of the series , We learned from redis Data structure and some advanced features of , Click the link below to look back < Explain in detail redis data structure ( Memory model ) And common commands > <redis Advanced applications ( ...

  8. Distributed cache technology redis Learning Series ( Two )—— Explain in detail redis data structure ( Memory model ) And common commands

    Redis data type And Memcached Simple only key-value The structure of the data record is different ,Redis The data types supported are much richer , There are five common data types :String.List.Hash.Set and Sor ...

  9. Distributed cache technology redis Study ( Four )——redis Advanced applications ( Cluster building 、 Cluster partition principle 、 Cluster operation )

    This article is about redis Learn the fourth part of the series , We learned from redis Data structure and some advanced features of , Click the link below to look back < Explain in detail redis data structure ( Memory model ) And common commands > <redis Advanced applications ( ...

  10. Distributed cache technology redis Study ( Two )—— Explain in detail redis data structure ( Memory model ) And common commands

    Redis data type And Memcached Simple only key-value The structure of the data record is different ,Redis The data types supported are much richer , There are five common data types :String.List.Hash.Set and Sor ...

Random recommendation

  1. asp.net And database operations

    <configuration> <system.web><compilation debug="true" targetFramework=" ...

  2. C# operation xml

    I'm working on a project , Need to use xml Make configuration file , But I forgot about it , So I went over it . Here's what I used in my project , So it's definitely not comprehensive . 1. newly build xml file using System.Xml;// Need to quote st ...

  3. VB.NET Basic course of database programming

    key word : By Luo Shan   as everyone knows ,VB.NET It does not have the function of operating the database itself , It processes the database through .NET FrameWork SDK In the database oriented programming class library and Microsoft's MDAC To achieve . among ,ADO. ...

  4. Wechat applet pull up login operation

    First step , Front end calls wx.login() Interface handle token Data requests come here , Second parts , hold tok Well, send it to the total server , And then wechat openid and assession Acquisition The third part is verification session Is it overdue , Overdue renewal ...

  5. php Second kill in the game

    Controller layer // seckill First of all, we have to judge the inventory Secondly, high concurrency And put it in storage public function goods_do() { $gid=input("get.gid"); $user_nam ...

  6. mpvue Use vant Weapp function npm run build The command is packaged and invalid

    Recently in use mpvue Develop wechat applet , Use like applets in the development process ui frame —— vant Weapp , As for how to use, there is an article on how to use in my personal blog vant Weapp , Please click here to check if you need . ...

  7. 【RS】Improving Implicit Recommender Systems with View Data - Use browsing data to enhance implicit recommendation system

    [ Paper title ]Improving Implicit Recommender Systems with View Data(IJCAI 18) [ Author of the paper ]Jingtao Ding  , Guanghui ...

  8. IO exercises

    1.Java Implementation of the nine nine multiplication table input to the text file public class Test1 { public static void main(String[] args) throws FileNotFoun ...

  9. Java Multithread synchronization method

    One . Synchronization method That is to say synchronized Methods of keyword modification .  because java Each object of has a built-in lock , When you decorate a method with this keyword ,  The built-in lock will protect the whole method . Before calling this method , Need to get built-in lock , Otherwise, it will be blocked . ...

  10. python Use progressbar Show progress bar

    progressbar install : pip install progressbar Use a # -*- coding=utf-8 -*- import time from progressbar impor ...