Table of Contents
memcached是什么?
memcached的特征
协议简单
基于libevent的事件处理
内置内存存储方式
memcached不互相通信的分布式
安装memcached
memcached的安装
memcached的启动
用客户端连接
使用Cache::Memcached
使用Cache::Memcached连接memcached
保存数据
获取数据
删除数据
增一和减一操作
总结
Home php教程 php手册 memcached完全剖析–1. memcached的基础

memcached完全剖析–1. memcached的基础

Jun 13, 2016 am 09:42 AM
dev http memcached Analyze publish Base of Link

发表日:2008/7/2 

原文链接:http://gihyo.jp/dev/feature/01/memcached/0001 

这个系列文章的链接在这里:

  • 第1次:http://www.phpchina.com/html/29/n-35329.html
  • 第2次:http://www.phpchina.com/html/30/n-35330.html
  • 第3次:http://www.phpchina.com/html/31/n-35331.html
  • 第4次:http://www.phpchina.com/html/32/n-35332.html href="http://www.phpchina.com/html/32/n-35332.html">
  • 第5次:http://www.phpchina.com/html/32/n-35333.html href="http://www.phpchina.com/html/32/n-35333.html"> href="http://www.phpchina.com/html/32/n-35332.html">

我是mixi株式会社开发部系统运营组的长野。 日常负责程序的运营。从今天开始,将分几次针对最近在Web应用的可扩展性领域 的热门话题memcached,与我公司开发部研究开发组的前坂一起, 说明其内部结构和使用。

  • memcached是什么?
  • memcached的特征
    • 协议简单
    • 基于libevent的事件处理
    • 内置内存存储方式
    • memcached不互相通信的分布式
  • 安装memcached
    • memcached的安装
    • memcached的启动
  • 用客户端连接
  • 使用Cache::Memcached
    • 使用Cache::Memcached连接memcached
    • 保存数据
    • 获取数据
    • 删除数据
    • 增一和减一操作
  • 总结

memcached是什么?

memcached 是以LiveJournal 旗下Danga Interactive 公司的Brad Fitzpatric 为首开发的一款软件。现在已成为 mixi、 hatena、 Facebook、 Vox、LiveJournal等众多服务中 提高Web应用扩展性的重要因素。

许多Web应用都将数据保存到RDBMS中,应用服务器从中读取数据并在浏览器中显示。 但随着数据量的增大、访问的集中,就会出现RDBMS的负担加重、数据库响应恶化、 网站显示延迟等重大影响。

这时就该memcached大显身手了。memcached是高性能的分布式内存缓存服务器。 一般的使用目的是,通过缓存数据库查询结果,减少数据库访问次数,以提高动态Web应用的速度、 提高可扩展性。

图1 一般情况下memcached的用途

memcached的特征

memcached作为高速运行的分布式缓存服务器,具有以下的特点。

  • 协议简单
  • 基于libevent的事件处理
  • 内置内存存储方式
  • memcached不互相通信的分布式

协议简单

memcached的服务器客户端通信并不使用复杂的XML等格式, 而使用简单的基于文本行的协议。因此,通过telnet 也能在memcached上保存数据、取得数据。下面是例子。

$ telnet localhost 11211 Trying 127.0.0.1... Connected to localhost.localdomain (127.0.0.1). Escape character is '^]'. set foo 0 0 3 (保存命令) bar (数据) STORED (结果) get foo (取得命令) VALUE foo 0 3 (数据) bar (数据)
Copy after login

协议文档位于memcached的源代码内,也可以参考以下的URL。

  • http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt

基于libevent的事件处理

libevent是个程序库,它将Linux的epoll、BSD类操作系统的kqueue等事件处理功能 封装成统一的接口。即使对服务器的连接数增加,也能发挥O(1)的性能。 memcached使用这个libevent库,因此能在Linux、BSD、Solaris等操作系统上发挥其高性能。 关于事件处理这里就不再详细介绍,可以参考Dan Kegel的The C10K Problem。

  • libevent: http://www.monkey.org/~provos/libevent/
  • The C10K Problem: http://www.kegel.com/c10k.html

内置内存存储方式

为了提高性能,memcached中保存的数据都存储在memcached内置的内存存储空间中。 由于数据仅存在于内存中,因此重启memcached、重启操作系统会导致全部数据消失。 另外,内容容量达到指定值之后,就基于LRU(Least Recently Used)算法自动删除不使用的缓存。 memcached本身是为缓存而设计的服务器,因此并没有过多考虑数据的永久性问题。 关于内存存储的详细信息,本连载的第二讲以后前坂会进行介绍,请届时参考。

memcached不互相通信的分布式

memcached尽管是“分布式”缓存服务器,但服务器端并没有分布式功能。 各个memcached不会互相通信以共享信息。那么,怎样进行分布式呢? 这完全取决于客户端的实现。本连载也将介绍memcached的分布式。

图2 memcached的分布式

接下来简单介绍一下memcached的使用方法。

安装memcached

memcached的安装比较简单,这里稍加说明。

memcached支持许多平台。

  • Linux
  • FreeBSD
  • Solaris (memcached 1.2.5以上版本)
  • Mac OS X

另外也能安装在Windows上。这里使用Fedora Core 8进行说明。

memcached的安装

运行memcached需要本文开头介绍的libevent库。Fedora 8中有现成的rpm包, 通过yum命令安装即可。

$ sudo yum install libevent libevent-devel
Copy after login

memcached的源代码可以从memcached网站上下载。本文执笔时的最新版本为1.2.5。 Fedora 8虽然也包含了memcached的rpm,但版本比较老。因为源代码安装并不困难, 这里就不使用rpm了。

  • 下载memcached:http://www.danga.com/memcached/download.bml

memcached安装与一般应用程序相同,configure、make、make install就行了。

$ wget http://www.danga.com/memcached/dist/memcached-1.2.5.tar.gz $ tar zxf memcached-1.2.5.tar.gz $ cd memcached-1.2.5 $ ./configure $ make $ sudo make install
Copy after login

默认情况下memcached安装到/usr/local/bin下。

memcached的启动

从终端输入以下命令,启动memcached。

$ /usr/local/bin/memcached -p 11211 -m 64m -vv slab class 1: chunk size 88 perslab 11915 slab class 2: chunk size 112 perslab 9362 slab class 3: chunk size 144 perslab 7281 中间省略 slab class 38: chunk size 391224 perslab 2 slab class 39: chunk size 489032 perslab 2 <23 server listening <24 send buffer was 110592, now 268435456 <24 server listening (udp) <24 server listening (udp) <24 server listening (udp) <24 server listening (udp)
Copy after login

这里显示了调试信息。这样就在前台启动了memcached,监听TCP端口11211 最大内存使用量为64M。调试信息的内容大部分是关于存储的信息, 下次连载时具体说明。

作为daemon后台启动时,只需

$ /usr/local/bin/memcached -p 11211 -m 64m -d
Copy after login

这里使用的memcached启动选项的内容如下。

选项说明-p使用的TCP端口。默认为11211-m最大内存大小。默认为64M-vv用very vrebose模式启动,调试信息和错误输出到控制台-d作为daemon在后台启动

上面四个是常用的启动选项,其他还有很多,通过

$ /usr/local/bin/memcached -h
Copy after login

命令可以显示。许多选项可以改变memcached的各种行为, 推荐读一读。

用客户端连接

许多语言都实现了连接memcached的客户端,其中以Perl、PHP为主。 仅仅memcached网站上列出的语言就有

  • Perl
  • PHP
  • Python
  • Ruby
  • C#
  • C/C++
  • Lua

等等。

  • memcached客户端API:http://www.danga.com/memcached/apis.bml

这里介绍通过mixi正在使用的Perl库链接memcached的方法。

使用Cache::Memcached

Perl的memcached客户端有

  • Cache::Memcached
  • Cache::Memcached::Fast
  • Cache::Memcached::libmemcached

等几个CPAN模块。这里介绍的Cache::Memcached是memcached的作者Brad Fitzpatric的作品, 应该算是memcached的客户端中应用最为广泛的模块了。

  • Cache::Memcached - search.cpan.org: http://search.cpan.org/dist/Cache-Memcached/

使用Cache::Memcached连接memcached

下面的源代码为通过Cache::Memcached连接刚才启动的memcached的例子。

#!/usr/bin/perl use strict; use warnings; use Cache::Memcached; my $key = "foo"; my $value = "bar"; my $expires = 3600; # 1 hour my $memcached = Cache::Memcached->new({ servers => ["127.0.0.1:11211"], compress_threshold => 10_000 }); $memcached->add($key, $value, $expires); my $ret = $memcached->get($key); print "$ret\n";
Copy after login

在这里,为Cache::Memcached指定了memcached服务器的IP地址和一个选项,以生成实例。 Cache::Memcached常用的选项如下所示。

选项说明servers用数组指定memcached服务器和端口compress_threshold数据压缩时使用的值namespace指定添加到键的前缀

另外,Cache::Memcached通过Storable模块可以将Perl的复杂数据序列化之后再保存, 因此散列、数组、对象等都可以直接保存到memcached中。

保存数据

向memcached保存数据的方法有

  • add
  • replace
  • set

它们的使用方法都相同:

my $add = $memcached->add( '键', '值', '期限' ); my $replace = $memcached->replace( '键', '值', '期限' ); my $set = $memcached->set( '键', '值', '期限' );
Copy after login

向memcached保存数据时可以指定期限(秒)。不指定期限时,memcached按照LRU算法保存数据。 这三个方法的区别如下:

选项说明add仅当存储空间中不存在键相同的数据时才保存replace仅当存储空间中存在键相同的数据时才保存set与add和replace不同,无论何时都保存

获取数据

获取数据可以使用get和get_multi方法。

my $val = $memcached->get('键'); my $val = $memcached->get_multi('键1', '键2', '键3', '键4', '键5');
Copy after login

一次取得多条数据时使用get_multi。get_multi可以非同步地同时取得多个键值, 其速度要比循环调用get快数十倍。

删除数据

删除数据使用delete方法,不过它有个独特的功能。

$memcached->delete('键', '阻塞时间(秒)');
Copy after login

删除第一个参数指定的键的数据。第二个参数指定一个时间值,可以禁止使用同样的键保存新数据。 此功能可以用于防止缓存数据的不完整。但是要注意,set函数忽视该阻塞,照常保存数据

增一和减一操作

可以将memcached上特定的键值作为计数器使用。

my $ret = $memcached->incr('键'); $memcached->add('键', 0) unless defined $ret;
Copy after login

增一和减一是原子操作,但未设置初始值时,不会自动赋成0。因此, 应当进行错误检查,必要时加入初始化操作。而且,服务器端也不会对 超过2 32时的行为进行检查。

总结

这次简单介绍了memcached,以及它的安装方法、Perl客户端Cache::Memcached的用法。 只要知道,memcached的使用方法十分简单就足够了。

下次由前坂来说明memcached的内部结构。了解memcached的内部构造, 就能知道如何使用memcached才能使Web应用的速度更上一层楼。 欢迎继续阅读下一章。

版权声明:可以任意转载,但转载时必须标明原作者charlee、原始链接以及本声明。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use magnet links How to use magnet links Feb 18, 2024 am 10:02 AM

Magnet link is a link method for downloading resources, which is more convenient and efficient than traditional download methods. Magnet links allow you to download resources in a peer-to-peer manner without relying on an intermediary server. This article will introduce how to use magnet links and what to pay attention to. 1. What is a magnet link? A magnet link is a download method based on the P2P (Peer-to-Peer) protocol. Through magnet links, users can directly connect to the publisher of the resource to complete resource sharing and downloading. Compared with traditional downloading methods, magnetic

How to download links starting with 115://? Download method introduction How to download links starting with 115://? Download method introduction Mar 14, 2024 am 11:58 AM

Recently, many users have been asking the editor, how to download links starting with 115://? If you want to download links starting with 115://, you need to use the 115 browser. After you download the 115 browser, let's take a look at the download tutorial compiled by the editor below. Introduction to how to download links starting with 115:// 1. Log in to 115.com, download and install the 115 browser. 2. Enter: chrome://extensions/ in the 115 browser address bar, enter the extension center, search for Tampermonkey, and install the corresponding plug-in. 3. Enter in the address bar of 115 browser: Grease Monkey Script: https://greasyfork.org/en/

Solution to win10 snmp installation failure error code 0x8024402C Solution to win10 snmp installation failure error code 0x8024402C Feb 13, 2024 am 08:30 AM

The snmp protocol is a simple network management protocol. This protocol can support the network management system and is used to monitor whether the devices connected to the network have any situation that causes management concern. However, many users have recently reported that the win10 installation of snmp failed with the error code 0x8024402C. what to do? Users can start Powershell as an administrator to set up. Let this site carefully introduce to users the solution to the error code 0x8024402C when installing snmp in win10. Solution to win10 snmp installation failure error code 0x8024402C 1. Start Powershell as administrator 1. The first step is to run the win10 system

How to get the WeChat video account link? How to add product links to WeChat video account? How to get the WeChat video account link? How to add product links to WeChat video account? Mar 22, 2024 pm 09:36 PM

As part of the WeChat ecosystem, WeChat video accounts have gradually become an important promotion tool for content creators and merchants. Getting links to video accounts on this platform is crucial for sharing and disseminating content. The following will introduce in detail how to obtain the WeChat video account link and how to add product links to the video account to improve the dissemination effect of the content. 1. How to get the WeChat video account link? After posting a video on your WeChat video account, the system will automatically create a video link. Authors can copy the link after publishing to facilitate sharing and dissemination. After logging in to your WeChat video account, you can browse the homepage of your video account. On the home page, each video is accompanied by a corresponding link so you can copy or share it directly. 3. Search video account: Enter the video account name in the WeChat search box

Detailed tutorial on installing Carla on Ubuntu 20.04 system. Detailed tutorial on installing Carla on Ubuntu 20.04 system. Feb 19, 2024 pm 08:20 PM

Carla is an open source autonomous driving simulation platform designed for developing and testing autonomous driving algorithms. The following is a detailed tutorial for installing Carla on Ubuntu20.04 system: Install dependencies: Open a terminal window and run the following command to install Carla’s dependencies: sudoaptupdatesudoaptinstall-ybuild-essentialclang-10llvm-10python3-pippython3-devlibpng-devlibjpeg-devlibtiff5-devlibopenexr -devlibhdf5-devlibsquish-de

What are the requirements for a video link? How to link the video account with goods? What are the requirements for a video link? How to link the video account with goods? Mar 07, 2024 pm 01:13 PM

With the popularity of short video platforms, more and more creators are beginning to use video accounts to create and promote content. Video accounts can not only showcase personal talents, but also realize commercial monetization through product links. However, to add a link to a video account, certain conditions must be met. 1. What are the requirements for a video link? Video account authentication is a prerequisite for adding links to your video account. Currently, major short video platforms such as Douyin and Kuaishou provide certification services, which mainly include two types: personal certification and institutional certification. Personal certification requires the submission of real identity information, while institutional certification requires the provision of certification materials from relevant companies or organizations. After completing the authentication, users can add links to their video accounts to enhance the credibility and authority of their accounts. One of the video link

Digital audio output interface on the motherboard-SPDIF OUT Digital audio output interface on the motherboard-SPDIF OUT Jan 14, 2024 pm 04:42 PM

SPDIFOUT connection line sequence on the motherboard. Recently, I encountered a problem regarding the wiring sequence of the wires. I checked online. Some information says that 1, 2, and 4 correspond to out, +5V, and ground; while other information says that 1, 2, and 4 correspond to out, ground, and +5V. The best way is to check your motherboard manual. If you can't find the manual, you can use a multimeter to measure it. Find the ground first, then you can determine the order of the rest of the wiring. How to connect motherboard VDG wiring When connecting the VDG wiring of the motherboard, you need to plug one end of the VGA cable into the VGA interface of the monitor and the other end into the VGA interface of the computer's graphics card. Please be careful not to plug it into the motherboard's VGA port. Once connected, you can

How to post updates on Tomato Novels How to post updates on Tomato Novels Feb 27, 2024 pm 05:30 PM

Tomato Novel, this popular novel reading software, not only has rich and diverse novel resources, but also provides exclusive categories so that every reader can easily find their favorite reading material. Whether it's a classic or a popular new work, Tomato Novels can satisfy your reading needs. You can also publish your own updates, share your reading opinions and experiences, and implement social functions. However, many friends do not know how to publish their own updates, so users who want to know more can come and learn more. Just give it a try. How to post updates on Tomato Novels? 1. First click to enter the My Page of Tomato Novel. 2. Then click on the avatar box to enter the personal information page. 3. Then click the edit pattern to publish the dynamic. 4. After filling in the content, select the publish button.

See all articles