memcached 性能_使用Memcached改善Web应用程序性能

memcached 性能

When we think of storage in a web application our first thought is usually a traditional database like MySQL. This is great for long term storage and data analysis, but there's a better option for many short-term needs: memcached. It's a great choice for saving bits of information between page requests and increasing performance. In this introduction we'll show you how to start using memcached with PHP.

当我们想到Web应用程序中的存储时,我们首先想到的通常是像MySQL这样的传统数据库。 这对于长期存储和数据分析非常有用,但是对于许多短期需求,还有一个更好的选择:内存缓存。 这是在页面请求之间节省信息位并提高性能的绝佳选择。 在本简介中,我们将向您展示如何开始在PHP中使用memcached。

介绍 (Introduction)

Memcached is simply a server with an interface to let you store things in memory. This can run on the same machine as your web server, but scalability comes from distributing instances across multiple servers. All you need is the memcached daemon running and PHP provides a simple interface with a PECL library. On a Debian-based Linux system this is as easy as:

Memcached只是具有接口的服务器,可用于将内容存储在内存中。 它可以与Web服务器在同一台计算机上运行,​​但可伸缩性来自在多个服务器之间分布实例。 您只需要运行memcached守护程序,PHP就可以使用PECL库提供简单的接口。 在基于Debian的Linux系统上,这很容易:

$ sudo apt-get install memcached
$ sudo service memcached start
$ sudo pecl install memcached
$ sudo service httpd restart


Now we should mention there are technically two PHP libraries available to work with memcached. The older library is called "memcache" and is lacking in some features. The newer "memcached" library uses libmemcached and is generally preferred.

现在,我们应该提到技术上有两个可用于memcachedPHP库。 较旧的库称为“内存缓存”,缺少某些功能。 较新的“ memcached”库使用libmemcached ,通常是首选。

The first step in PHP is to connect to the server. Connections can be persisted across requests, which is nice for performance. Then add to the server list as needed. In this case we'll use a locally running instance on the default port:

PHP的第一步是连接到服务器。 可以在请求之间保留连接,这对性能很有好处。 然后根据需要添加到服务器列表。 在这种情况下,我们将在默认端口上使用本地运行的实例:


function get_memcached() {
    // Set a persistent connection ID
    $mc = new Memcached('webapp');
    // Set a short timeout (in milliseconds) so if the server goes down
    // it doesn't take down our site with it
    $mc->setOption(Memcached::OPT_CONNECT_TIMEOUT, 1000);
    if ( !$mc->getServerList() ) {
        if ( !$mc->addServer('localhost', 11211) ) {
            error_log('Could not add memcached server.');
            return false;
        }
    }
    return $mc;
}


Now you can read and write PHP variables to memcached with simple functions based on keys you define. They'll be serialized and deserialized automatically. You can't write resources like database connections or result sets, but you can turn those result sets into arrays and store those.

现在,您可以根据定义的键,使用简单的函数将PHP变量读写到memcached中。 它们将被自动序列化和反序列化。 您不能编写诸如数据库连接或结果集之类的资源,但是可以将这些结果集转换为数组并进行存储。


$mc->set('list', array(1, 2, 3));
$list = $mc->get('list');


储存资料 (Storing Data)

Let's say we want to store a list of recently visited URLs for each logged in user. We could use sessions but that wouldn't work across devices and it'll disappear as soon as the session is cleared. We could use a database but that's slow for this kind of data that's most likely not critical to our system. Using memcached this is easy:

假设我们要为每个登录用户存储最近访问的URL列表。 我们可以使用会话,但是不能在所有设备上使用,并且一旦清除会话,它将消失。 我们可以使用数据库,但是对于这类对我们的系统而言并非至关重要的数据而言,速度很慢。 使用memcached很简单:


$user_id = 123;  // The current user's ID

$recents = array();
if ($mc = get_memcached()) {
    // Get any stored in memcached
    $recents = $mc->get("recents-$user_id");
    if (!$recents) {
        $recents = array();
    }
    $recents[] = $_SERVER['REQUEST_URI'];
    $recents = array_unique($recents);
    $mc->set("recents-$user_id", $recents);
}

print_r($recents);


快取 (Caching)

Now let's really boost your web application by caching database results. Database queries are usually the biggest bottleneck in server processing, so avoiding duplicate queries by caching results in memory can provide a huge performance gain. The simplest method is to query and store just with primary keys. Typically it's best that the cached value be deleted when the database record is updated so a user never sees any out-of-date values.

现在, 通过缓存数据库结果来真正增强您的Web应用程序 。 数据库查询通常是服务器处理中的最大瓶颈,因此通过将结果缓存在内存中来避免重复查询可以极大地提高性能。 最简单的方法是仅使用主键进行查询和存储。 通常,最好在更新数据库记录时删除缓存的值,这样用户就永远不会看到任何过期的值。


function store_product($id, $name, $price) {
    // Create or update the product in the database
    $db = get_db();
    $qry = $db->prepare('REPLACE INTO product (id, name, price) VALUES (:id, :name, :price)');
    $qry->bindParam(':id', $id);
    $qry->bindParam(':name', $name);
    $qry->bindParam(':price', $price);
    $qry->execute();

    // Remove outdated values from cache if it's there
    if ($mc = get_memcached()) {
        $mc->delete("product-$id");
    }
}

function get_product($id) {
    $product = null;

    // First check the cache
    if ($mc = get_memcached()) {
        $product = $mc->get("product-$id");
    }

    if (!$product) {
        // Not in the cache; check the db
        $qry = $db->prepare('SELECT * FROM product WHERE id = $id');
        $qry->bindParam(':id', $id);
        if ($qry->execute()) {
            $product = $qry->fetch();

            // Cache for future use
            if ($mc) {
                $mc->set("product-$id", $product);
            }
        }
    }

    return $product;
}


注意事项 (Caveats)

As with any technology choice there are limitations and things to watch out for:

与任何技术选择一样,存在局限性和注意事项:

  • The max length of a key is 250 bytes. Keep your keys simple and short.

    密钥的最大长度为250个字节。 保持键简明扼要。
  • The default max value size is about 1MB. This isn't the right place to store large values.

    默认最大值为1MB。 这不是存储大值的正确位置。
  • Storage isn't locked for reading or writing in the way database records can be locked. Just be aware that any web request can update any value at any time.

    未锁定存储以读取或写入可锁定数据库记录的方式。 请注意,任何Web请求都可以随时更新任何值。
  • Be sure your memcached servers have enough combined RAM.

    确保您的内存缓存服务器具有足够的组合RAM。

下一步 (Next Steps)

There's more you can do with memcached:

您可以使用memcached做更多的事情:

  • Cached values can have timeouts. This is useful when data should be cached for a set period of time instead of deleted manually.

    缓存的值可能会超时。 当数据应缓存一定时间而不是手动删除时,此功能很有用。
  • Simple increment and decrement methods are useful for keeping quick counters between requests.

    简单的incrementdecrement方法对于保持请求之间的快速计数器很有用。

  • With memcached configured correctly you can share data between applications written in many programming languages.

    正确配置memcached后,您就可以在以多种编程语言编写的应用程序之间共享数据。

Give memcached a try. In the right scenarios it's a very simple and effective solution to maximize your web app performance.

尝试一下memcached。 在正确的情况下,这是一个非常简单有效的解决方案,可最大化您的Web应用性能。

翻译自: https://davidwalsh.name/memcached-intro

memcached 性能

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值