Memcached实际项目应用

在Memcached官方的GitHub上,可以找到这么一个文档——HowTo.txt

Howto
=====

Basic Example:
==============

Lets say you have 3 servers.  Server 1 and server 2 have 3GB of space
and server 3 has 2GB of space for cache.  Here is how I would set up
my client.
-----------------------------------------------------------------------------
import com.danga.MemCached.*;
public class MyClass {

    // create a static client as most installs only need
    // a single instance    // 创建一个MemCachedClient客户端,用于从MemcachedServer进行交互
    protected static MemCachedClient mcc = new MemCachedClient();

    // set up connection pool once at class load
    static {

       // server list and weights    // 因为一个客户端(例如你的Web 应用)可能会访问多个服务器。    // 使用Java客户端事,默认Windows 版的Memcached服务的端口默认是11211
        String[] servers =
            {
              "server1.mydomain.com:1624",
              "server2.mydomain.com:1624",
              "server3.mydomain.com:1624"
            };

        Integer[] weights = { 3, 3, 2 };

        // grab an instance of our connection pool
        SockIOPool pool = SockIOPool.getInstance();

        // set the servers and the weights
        pool.setServers( servers );
        pool.setWeights( weights );

        // set some TCP settings
        // disable nagle
        // set the read timeout to 3 secs
        // and don‘t set a connect timeout
        pool.setNagle( false );
        pool.setSocketTO( 3000 );
        pool.setSocketConnectTO( 0 );

        // initialize the connection pool
        pool.initialize();
    }

    // from here on down, you can call any of the client calls
    public static void examples() {    // 存储数据到缓存服务器
        mcc.set( "foo", "This is a test String" );    // 从服务器取数
        String bar = mcc.get( "foo" ).toString();
    }
}
-------------------------------------------------------------------------------
Multi-client Example:
=====================

If you need to support multiple clients (i.e. Java, PHP, Perl, etc.)
you need to make a few changes when you are setting things up:
-----------------------------------------------------------------
    // use a compatible hashing algorithm
    pool.setHashingAlg( SockIOPool.NEW_COMPAT_HASH );
-------------------------------------------------------------------

Serialization:
==============
For java "native types", which include:

Boolean
Byte
String
Character
StringBuffer
StringBuilder
Short
Long
Double
Float
Date
Integer

The client will by default NOT use java serialization, and instead
will serialize using the primitive values to save space.

For other java objects, you have 2 options to serialize the java objects.
one is make sure the class implements Serializable in order to be able
to be stored with default object transcoder provided by this client;
The other alternative is to write your own transcoder to do the serialization
and deserialization by yourself, the following is simple example:
-------------------------------------------------------------------------
package com.schooner.MemCached;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
/**
 * {@link ObjectTransCoder} is the default TransCoder used to handle the
 * serialization and deserialization in memcached operations.
 *
 * @author Xingen Wang
 * @see AbstractTransCoder
 * @see TransCoder
 */
public class ObjectTransCoder extends AbstractTransCoder {

    /*
     * (non-Javadoc)
     *
     * @see com.schooner.MemCached.TransCoder#decode(InputStream)
     */
    public Object decode(final InputStream input) throws IOException {
        Object obj = null;
        ObjectInputStream ois = new ObjectInputStream(input);
        try {
            obj = ois.readObject();
        } catch (ClassNotFoundException e) {
            throw new IOException(e.getMessage());
        }
        ois.close();
        return obj;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * com.schooner.MemCached.AbstractTransCoder#encode(java.io.OutputStream,
     * java.lang.Object)
     */
    public void encode(final OutputStream output, final Object object) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(output);
        oos.writeObject(object);
        oos.close();
    }

    public Object decode(byte[] input){
        Object obj = null;
        try {
            ObjectInputStream ois = new ObjectInputStream(
                    new ByteArrayInputStream(input));
            obj = ois.readObject();
            ois.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return obj;
    }
}
-----------------------------------------------------------------------------------------
After that, you should set transcoder to your client:
-----------------------------------------------------------------------------
MemCachedClient mc = new MemCachedClient();
mc.setTransCoder(new YourTransCoder());
-----------------------------------------------------------------------------

I would also recommend that if possible, classes should instead
implement Externalizable as opposed to Serializable or write the
transcoder by your self.  This allows the
author of the class to define how objects of that class should
serialize.  In practice at Meetup.com, we saw a 60% reduction in the size
of our serialized objects by doing this.  This means less data to eat up
cache space and less data to transfer over the network.

binary protocol:
================
In Schooner‘s implementation, binary protocol for memcached has been implemented, and
due to our test performance increased about 5% overall, but you have to use
memcached 1.4+ in the server side to support this features.
The following code snipets shows how to use this feature:
-----------------------------------------------------------------------------
mc = new MemCachedClient(true, true);
-----------------------------------------------------------------------------

UDP protocol:
=============
In schooner‘s implementation, UDP protocol for memcached is also supported. While due
to our test, the performance is not that good as tcp protocol, we are still working on
performance tuning.
In our latest implementation, UDP protocol works in asynchronized mode.
We recommend user memcached 1.4.4+ when UDP protocol is used.
-----------------------------------------------------------------------------
mc = new MemCachedClient(false, false);
-----------------------------------------------------------------------------

Other:
======
See the java docs.

上面的第一个例子中:

如果第一次执行examples()后,会在服务器上存储key为‘foo’的对象。

如果客户端执行完毕后,把examples()改为

public static void examples() {

     //   mcc.set( "foo", "This is a test String" );    
        String bar = mcc.get( "foo" ).toString();
    }

也就是不再设置key=‘foo‘的值,而是直接取数,这样也是可以取到的。

在实际开发中,一般用于和数据库交互前后。如果是查询数据://1)从缓存服务器查询取数//2)如果取到,就直接返回,不再从数据库取数。没有取到,才从数据库查询取数。//3)取数完毕,将数据在缓存服务器存储一份。

// 如果是更新操作://1)直接对数据库进行更新操作//2) 将数据在缓存服务器也更新。

Memcached实际项目应用,布布扣,bubuko.com

时间: 2024-10-21 02:11:59

Memcached实际项目应用的相关文章

Key/Value之王Memcached初探:二、Memcached在.Net中的基本操作

一.Memcached ClientLib For .Net 首先,不得不说,许多语言都实现了连接Memcached的客户端,其中以Perl.PHP为主. 仅仅memcached网站上列出的语言就有:Perl.PHP.Python.Ruby.C#.C/C++以及Lua等. 那么,我们作为.Net码农,自然是使用C#.既然Memcached客户端有.Net版,那我们就去下载一个来试试. 下载文件:http://pan.baidu.com/s/1w9Q8I memcached clientlib项目

memcached讲解

Memcached 最近空闲的是时候研究了一下缓存,根据公司环境对缓存进行了系统的了解,我们使用memcacheed进行缓存,下面结合我的 理解,以及网上的相关资料,memecached进行讲解. memcached是一个开源的高性能分布式内存对象缓存系统.其实思想还是比较简单的,实现包括server端(memcached开源项目一般只单指server端)和client端两部分: 1.server端本质是一个in-memory key-value store,通过在内存中维护一个大的hashma

【转载】Memcached在.Net中的基本操作

一.Memcached ClientLib For .Net 首先,不得不说,许多语言都实现了连接Memcached的客户端,其中以Perl.PHP为主. 仅仅memcached网站上列出的语言就有:Perl.PHP.Python.Ruby.C#.C/C++以及Lua等. 那么,我们作为.Net码农,自然是使用C#.既然Memcached客户端有.Net版,那我们就去下载一个来试试. 下载文件:http://pan.baidu.com/s/1w9Q8I memcached clientlib项目

memcached c#

1.下载Memcached For Windows URL:http://code.jellycan.com/files/memcached-1.2.6-win32-bin.zip 2.管理员身份运行cmd 3.在Windows中安装Memcached服务:memcached.exe -d install(那么,对应卸载命令为:memcached.exe -d uninstall) 4.启动 net start "Memcached Server" 5.停止服务 net stop &q

Python Memcached Script

介绍 利用 python 书写了 memcached 的启动等一类操作 尽量的实现脚本的复用性,以及脚本的可扩展性,已达到一劳永逸的效果, 并且添加了 memcached 监控搭建 memcached 操作代码 #!/usr/bin/env python # _*_coding:utf-8_*_ # Author: "Edward.Liu" # Author-Email: [email protected] import psutil import argparse import sy

memcached 学习笔记 4

memcached真实项目中的应用 1 缓存式的Web应用程序架构 有了缓存的支持,我们可以在传统的app层和db层之间加入cache层,每个app服务器都可以绑定一个mc, 每次数据的读取都可以从ms中取得,如果没有,再从db层读取. 而当数据要进行更新时,除了要发送update的sql给db层,同时也要将更新的数据发给mc,让mc去更新ms中的数据. 假设今后我们的数据库可以和ms进行通讯了,那可以将更新的任务统一交给db层, 每次数据库更新数据的同时会自动去更新ms中的数据,这样就可以进一

java操作memcached入门教程demo代码

原文:java操作memcached入门教程demo代码 源代码下载地址:http://www.zuidaima.com/share/1550463754996736.htm 参考地址: http://www.open-open.com/lib/view/open1357831114183.html http://tech.idv2.com/2008/07/10/memcached-001/ 感谢 京-java牛-ID号1  感谢 锡-SuperPrivate-195 在网上搜索了部分代码,一个

【转】 Key/Value之王Memcached初探:二、Memcached在.Net中的基本操作

一.Memcached ClientLib For .Net 首先,不得不说,许多语言都实现了连接Memcached的客户端,其中以Perl.PHP为主. 仅仅memcached网站上列出的语言就有:Perl.PHP.Python.Ruby.C#.C/C++以及Lua等. 那么,我们作为.Net码农,自然是使用C#.既然Memcached客户端有.Net版,那我们就去下载一个来试试. 下载文件:http://pan.baidu.com/s/1w9Q8I memcached clientlib项目

simple-spring-memcached缓存搭建

项目中使用的缓存经常是知道使用,没有试过搭建起它.刚好这次自己的毕业可以用来搭建缓存.其他不多说了,直接看操作吧.首先在pom.xml中依赖simple-spring-memcached的架包. 1 <dependency> 2 <groupId>com.google.code.simple-spring-memcached</groupId> 3 <artifactId>xmemcached-provider</artifactId> 4 &l