Memcache升級版之CouchBase [三]JAVA應用詳解

Step 1:獲取java library

在官網http://www.couchbase.com下載對應Jar版本(目前是1.1.9).若您是Maven項目使用如下方式即可
<repositories>
  <repository>
    <id>couchbase</id>
    <name>Couchbase Maven Repository</name>
    <url>http://files.couchbase.com/maven2/</url>
  </repository>
</repositories>
 
<dependencies>
  <dependency>
    <groupId>couchbase</groupId>
    <artifactId>couchbase-client</artifactId>
    <version>1.1.9</version>
  </dependency>
</dependencies>

Step 2:快來牛刀小試一把

import com.couchbase.client.CouchbaseClient;

import java.net.URI;
import java.util.Arrays;
import java.util.List;

public class Hello {

	public static void main(String[] args) throws Exception {
		// (Subset) of nodes in the cluster to establish a connection
		List<URI> hosts = Arrays.asList(new URI(
				"http://10.18.138.76:8091/pools"));
		// Name of the Bucket to connect to
		String bucket = "default";
		// Password of the bucket (empty) string if none
		String password = "";
		// Connect to the Cluster
		CouchbaseClient client = new CouchbaseClient(hosts, bucket, password);

		/*
		 * Store a Document 
		 * 1.client.set("hardy-couchbase-001","Hello Couchbasesss111111!")
		 * 2.Retreive the Document and print it: client.get("hardy-couchbase-001")
		 */
		client.set("hardy-couchbase-001","Hello hardy-couchbase-001");
		client.set("order_assign-001","Hello order_assign-001");
		client.set("order_assign-002","Hello order_assign-002");
		
		System.out.println(client.get("hardy-couchbase-001") +" : "+client.get("order_assign-001"));
		
		client.delete("hardy-couchbase-001");

		// Shutting down properly
		client.shutdown();
	}
}

Step 3:應用拓展

3.1條件查詢key
  1打開Couchbase的管理後臺,切換到Views選項卡
    2創建“Create Development View”,分別輸入{document name=desdoc(前綴_design/dev_不用管,發佈後用輸入的名字即可),view name=vname}
    3)創建完後,在views會看到剛創建的 development view,點下Publish即發佈
    4)這樣就可以查詢所需要的Key了,代碼如下
/*
		 * Querying Views :
		 * 1: Load the View infos
		 * 2: Create a Query object to customize the Query
		 * 3: Actually Query the View and return the results
		 * 4: Iterate over the Data and print out the full document
		 */
		View view = client.getView("desdoc", "vname");
		
		Query query = new Query().setIncludeDocs(true);
		query.setRangeStart("order_assign"); 
		query.setRangeEnd("order_assign\\uefff");
		query.setLimit(2);
		
		ViewResponse response = client.query(view, query);
		
		for (ViewRow row : response) {
		  System.out.println(row.getKey()+" =:= "+row.getDocument());
		}
     5)運行結果打印
     order_assign-001 =:= Hello order_assign-001
     order_assign-002 =:= Hello order_assign-002




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