Memcache學習筆記一:Memcache在Linux下的安裝和使用

Memcache學習筆記一:Memcache在Linux下的安裝和使用

標籤(空格分隔): Memcache


一、下載Memcache源碼包

二、安裝Memcache 源碼編譯安裝

  1. gcc依賴 可在線安裝yum install gcc
  2. lib-event 可在線安裝yum install lib-event

    含有文件:
        libevent          
        libevent-doc    
        libevent-headers
        libevent-devel
    

    手動安裝:進入lib-event目錄,執行: rpm -ivh libevent-*

  3. 編譯安裝memcache

    [root@mo memcached-1.4.31]# ./configure 
    [root@mo memcached-1.4.31]# make

    成功之後文件夾中會出現一個memcached的可執行文件

  4. 啓動

    //查看memcache的啓動命令
    [root@mo memcached-1.4.31]# ./memcached -help
    //啓動命令:
    [root@mo memcached-1.4.31]#./memcached -p 11211 -vvv -u root

三、Memcache的API操作

連接Memecache驅動包:spymemcached-x.x.x.jar,xmemcached-x.x.x.jar, memcache-x.x.x.jar

使用較多的是xmemcached-x.x.x.jar
官網下載xmemcached-1.4.3-bin-with-dependencies.tar.gz
解壓:含有用戶指南和xmemcached-x.x.x.jar和依賴jar
  1. 導入jar包

    xmemcached-1.4.3.jar
    slf4j-log4j12-1.6.1.jar
    slf4j-api-1.6.1.jar
    log4j-1.2.16.jar
    
  2. API操作

    import net.rubyeye.xmemcached.*;
    import net.rubyeye.xmemcached.command.BinaryCommandFactory;
    import net.rubyeye.xmemcached.exception.MemcachedException;
    import net.rubyeye.xmemcached.utils.AddrUtil;
    import org.junit.Before;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.util.Date;
    import java.util.concurrent.TimeoutException;
    
    /**
     * Created by MOTUI on 2016/10/19.
     *
     * xmemcached操作Memcache
     */
    public class TestCache {
    
        private MemcachedClient client;
    
        @Before
        public void before() throws IOException {
            //獲得XMemcachedClientBuilder對象
            XMemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("192.168.0.167:11211"));
            //添加二進制協議
            builder.setCommandFactory(new BinaryCommandFactory());
            //獲得MemcachedClient
            client = builder.build();
        }
    
        /**
         * 添加
         * @throws InterruptedException
         * @throws MemcachedException
         * @throws TimeoutException
         */
        @Test
        public void testAdd() throws InterruptedException, MemcachedException, TimeoutException {
            //100秒
            boolean flag = client.add("user:1", 100, "zhangsan");
            //boolean flag = client.add("user:2", 100, "zhangsan");
            System.out.println(flag);
        }
    
        /**
         * 獲取
         * @throws InterruptedException
         * @throws MemcachedException
         * @throws TimeoutException
         */
        @Test
        public void testGet() throws InterruptedException, MemcachedException, TimeoutException {
            Object object = client.get("user:1");
            //Object object = client.get("user:2");
            System.out.println(object);
        }
    
        /**
         * 保存或修改
         * @throws InterruptedException
         * @throws MemcachedException
         * @throws TimeoutException
         */
        @Test
        public void testSaveOrUpdate() throws InterruptedException, MemcachedException, TimeoutException {
            boolean flag = client.set("user:1", 1000, "wangwu");
            System.out.println(flag);
        }
    
        /**
         * 更新
         * @throws InterruptedException
         * @throws MemcachedException
         * @throws TimeoutException
         */
        @Test
        public void testUpdate() throws InterruptedException, MemcachedException, TimeoutException {
            boolean flag = client.replace("user:1", 1000, new Date());
            System.out.println(flag);
        }
    
        /**
         * 刪除
         * @throws TimeoutException
         * @throws InterruptedException
         * @throws MemcachedException
         */
        @Test
        public void testDelete() throws TimeoutException, InterruptedException, MemcachedException{
            boolean flag = client.delete("user:1");
            System.out.println(flag);
        }
    
    
        /**
         * Memcached是通過cas協議實現原子更新,所謂原子更新就是compare and set
         * @throws InterruptedException
         * @throws MemcachedException
         * @throws TimeoutException
         */
        @Test
        public void testCAS() throws InterruptedException, MemcachedException, TimeoutException {
            GetsResponse<Object> response = client.gets("user:2");
            //版本號
            long version = response.getCas();
    
            System.out.println(version);
            //修改
            boolean flag = client.cas("user:2", 100, "update-user:2", version);
            System.out.println(flag);
    
        }
    
        @Test
        public void testCAS1() throws InterruptedException, MemcachedException, TimeoutException {
            boolean flag = client.cas("user:1", new CASOperation<Object>() {
                @Override
                public int getMaxTries() {
                    return 1;
                }
    
                @Override
                public Object getNewValue(long l, Object o) {
                    return "update-user:1";
                }
            });
            System.out.println(flag);
    
        }
    
        /**
         * 修改時間不修改值
         * @throws InterruptedException
         * @throws MemcachedException
         * @throws TimeoutException
         */
        @Test
        public void testTouch() throws InterruptedException, MemcachedException, TimeoutException {
            boolean flag = client.touch("user:1", 1000);
            System.out.println(flag);
        }
    
        /**
         * 需要開啓二進制協議
         * @throws InterruptedException
         * @throws MemcachedException
         * @throws TimeoutException
         */
        @Test
        public void testGetAndTouch() throws InterruptedException, MemcachedException, TimeoutException {
            Object object = client.getAndTouch("user:1", 1000);
            System.out.println(object);
        }
    
        /**
         * 設置命名空間
         * @throws InterruptedException
         * @throws MemcachedException
         * @throws TimeoutException
         */
        @Test
        public void testWithNameSpace() throws InterruptedException, MemcachedException, TimeoutException {
            client.beginWithNamespace("com.motui.test");
            boolean flag = client.set("user:01", 100, "nameSpace");
            System.out.println(flag);
            Object object = client.get("user:01");
            System.out.println(object);
        }
    
        @Test
        public void testWithNameSpace01() throws InterruptedException, MemcachedException, TimeoutException {
            Object object = client.withNamespace("com.motui.test2", new MemcachedClientCallable<Object>() {
                @Override
                public Object call(MemcachedClient memcachedClient) throws MemcachedException, InterruptedException, TimeoutException {
                    client.set("user:01", 1000, "test2-nameSpace");
                    Object object = client.get("user:01");
                    return object;
                }
            });
            System.out.println(object);
        }
    
        /**
         * 清除指定命名空間的緩存
         * @throws InterruptedException
         * @throws MemcachedException
         * @throws TimeoutException
         */
        @Test
        public void testClearWithNameSpace() throws InterruptedException, MemcachedException, TimeoutException {
            client.invalidateNamespace("com.motui.test");
        }
    
        /**
         * 清除所有緩存
         * @throws InterruptedException
         * @throws MemcachedException
         * @throws TimeoutException
         */
        @Test
        public void clearAll() throws InterruptedException, MemcachedException, TimeoutException {
            client.flushAll();
        }
    
    }
    

    四、Memcache和Redis的比較和應用場景

    Memcache :分佈式緩存服務 key-value  基於內存 最大緩存時長30天  key-value 最大 不得超過1M
          Memcache單節點服務器不支持集羣.
          key String    value:Object
    
    Redis  :基於內存數據庫 數據持久化 基於內存 key-value 緩存 key-value 最大 1GB
              Redis 支持集羣 (主從/副本集+分片)
              key String   value:String/List/Set(SortedSet)/Map 
    
              SETEX(key,value,expire) 
    
    Memcache使用場景:
               1.分佈式cache  <-->  數據庫靜默   查
               2.分佈式session管理  提升應用服務器的健壯性 減輕服務器的內存壓力
    

五、Memcache的分佈

    Memcached的分佈是通過客戶端實現的,客戶端根據key的哈希值得到將要存儲的memcached節點,
並將對應的value存儲到相應的節點。

啓動另一個Memcache:

[root@mo memcached-1.4.31]# ./memcached -p 11212 -vvv -u root

對於集羣的連接只需要修改連接代碼即可,因爲xmemcached已經幫我們做好了連接的解決方案。修改如下:

    import net.rubyeye.xmemcached.*;
    import net.rubyeye.xmemcached.command.BinaryCommandFactory;
    import net.rubyeye.xmemcached.exception.MemcachedException;
    import net.rubyeye.xmemcached.utils.AddrUtil;
    import org.junit.Before;
    import org.junit.Test;

    import java.io.IOException;
    import java.util.Date;
    import java.util.concurrent.TimeoutException;

    /**
     * Created by MOTUI on 2016/10/19.
     *
     * xmemcached操作Memcache
     */
    public class TestCache01 {

        private MemcachedClient client;

        @Before
        public void before() throws IOException {
            //獲得XMemcachedClientBuilder對象
            //多個[ip]:[port]中間用空格分割
            //一旦集羣搭建完成,多個[ip]:[port]的順序不能隨意改變,順序改變會導致數據無法取到
            XMemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("192.168.0.167:11211 192.168.0.167:11212"));
            //添加二進制協議
            builder.setCommandFactory(new BinaryCommandFactory());
            //獲得MemcachedClient
            client = builder.build();
        }

        /**
         * Memcache集羣測試
         * @throws TimeoutException
         * @throws InterruptedException
         * @throws MemcachedException
         */
        @Test
        public void testCluster() throws TimeoutException, InterruptedException, MemcachedException{
            for(int i=0;i<100;i++){
                //插入數據
                //client.set("key"+i, 1000, "value"+i);
                //查數據
                String key="key"+i;
                int dbNum=Math.abs(key.hashCode())%2;

                System.out.println("機器編號:"+dbNum+" > "+client.get(key));
            }
        }
    }

結果可自行測試。

注意:

多個[ip]:[port]中間用空格分割
一旦集羣搭建完成,多個[ip]:[port]的順序不能隨意改變,順序改變會導致數據無法取到

其他配置參考xmemcached官方使用文檔。在官方下載的.zip包下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章