Membase,Memcached,Couchbase1.8 JAVA 簡單調用 操作

 

昨天寫了關於 C#版操作Membase的實例 http://blog.csdn.net/qq415734794/article/details/7865716 

今天分享個JAVA的操作實例吧:

首先還是下載JAVA版的client包吧: http://packages.couchbase.com/clients/java/1.0.3/Couchbase-Java-Client-1.0.3.zip 裏面就是些JAR包

我本機WIN7 64位 ,使用的是myeclipse。

新建一個Maven項目

完成後,在下圖紅線框所示的位置添加Membase的引用jar包

接着我們在App.java文件中寫如下的code:

package MavenApp;

import java.util.concurrent.TimeUnit;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.MemcachedClient;

/**
 * Hello world!
 * 
 */
public class App {
	public static void main(String[] args) {
		//定義一個client
		MemcachedClient client;
		try {
			//實例化client,爲client指定數據庫地址
			client = new MemcachedClient(AddrUtil.getAddresses("10.1.18.45:11211"));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return;
		}
		//獲取名爲item的鍵值對
		Object item = client.get("item");		
		if (item == null) {
			System.out.println("未找到item對象!");
			System.out.println("正在插入item對象!");
			client.set("item", 10, "Hello World! I am Billy.lee!");
			System.out.println("插入item對象成功,請再次運行獲取此對象數據!");
		} else {
			//輸出內容
			System.out.println((String) item);
		}
		client.waitForQueues(1, TimeUnit.MINUTES);
		System.exit(0);
	}
}

接着我們在AppTest.java文件中寫如下code:

package MavenApp;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit test for simple App.
 */
public class AppTest 
    extends TestCase
{
    /**
     * Create the test case
     *
     * @param testName name of the test case
     */
    public AppTest( String testName )
    {
        super( testName );
    }

    /**
     * @return the suite of tests being tested
     */
    public static Test suite()
    {
        return new TestSuite( AppTest.class );
    }

    /**
     * Rigourous Test :-)
     */
    public void testApp()
    {
    	App.main(null);
    }
}

在testApp()方法上右鍵,進行JUnit測試

第一次運行,如下圖:

第二次運行,如下圖:

 

至此,JAVA版的操作完成!

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