couchbase笔记

2022-04-11 00:00:00 数据 连接 缓存 配置文件 有误

近在做一个项目,用到了couchbase,正好项目组里也有个大牛,他自己先把couchbase搞的差不多,我就拿个现成的,理解消化一下,然后再融会贯通,算是入门吧。

再有就是好记性不如烂笔头,还是要记录一下,免得将来忘记。


1、couchbase连接

couchbase连接摸索出来了两种方式,各有不同的用法,下面来一一说明。


种是创建Cluster连接,然后通过Cluster来创建bucket,具体代码如下。

Cluster cluster = CouchbaseCluster.create(path);//path指具体的couchbase服务路径
cluster.openBucket(bucketName,30,TimeUnit.SECONDS);//30是指打开couchbase桶的超时时间,TimeUnit.SECONDS指超时时间的单位,在此为秒
cluster.openbucket(bucketName,password,30,TimeUnit.SECONDS);//此处多了一个password,这个password是桶密码,couchbase可以为桶设置密码


第二种是创建CouchbaseClient,这种方法目前网上技术文档比较多

List<URI> uris = new LinkedList<URI>();
uris.add(URI.create(path));//path值具体的couchbase服务路径
CouchbaseClient client = client = new CouchbaseClient(uris, bucketName, password);


这些只是基础的连接代码,如果真要在项目中用,这些代码还需要改造,在这里就贴出来改造过后的代码

改造过后的代码仍然有两种方式,种创建Cluster连接

public class CouchBaseUtils {

private static String couchBasePath;
private static Cluster cluster;
private static List<String> couchBasePathList = new ArrayList<String>();
private static Map<String,Bucket> bucketMap = new HashMap<String, Bucket>();
static{
couchBasePath = APPPropertisUtils.getProperty("couchBase.Server.path");
}

//初始化化缓存相关配置,外部必须显示调用此方法
public static void init() {
cluster = CouchbaseCluster.create(getCouchBasePathList(couchBasePath));
bucketMap.put(getBucketName(APPPropertisUtils.getProperty("couchBase.website_product")),openBucket(getBucketName(APPPropertisUtils.getProperty("couchBase.website_product")),getBucketPwd(APPPropertisUtils.getProperty("couchBase.website_product"))));
bucketMap.put(getBucketName(APPPropertisUtils.getProperty("couchBase.website_company")),openBucket(getBucketName(APPPropertisUtils.getProperty("couchBase.website_company")),getBucketPwd(APPPropertisUtils.getProperty("couchBase.website_company"))));
bucketMap.put(getBucketName(APPPropertisUtils.getProperty("couchBase.website_product_group")),openBucket(getBucketName(APPPropertisUtils.getProperty("couchBase.website_product_group")),getBucketPwd(APPPropertisUtils.getProperty("couchBase.website_product_group"))));
bucketMap.put(getBucketName(APPPropertisUtils.getProperty("couchBase.website_fundmanager")),openBucket(getBucketName(APPPropertisUtils.getProperty("couchBase.website_fundmanager")),getBucketPwd(APPPropertisUtils.getProperty("couchBase.website_fundmanager"))));
AppLogUtils.info("缓存服务器连接成功...");
}

/**
* 打开桶
* @param bucketName 桶名
* @param password 密码
* @return
*/
private static Bucket openBucket(String bucketName,String password) {
if(StringUtils.isEmpty(password)) {
return cluster.openBucket(bucketName,30,TimeUnit.SECONDS);
} else {
return cluster.openBucket(bucketName,password,30,TimeUnit.SECONDS);
}
}

public static List<String> getCouchBasePathList(String path){
if(path.contains(",")){
String[] arrayOne = path.split("\\,");
for(int i = 0;i < arrayOne.length;i++){
couchBasePathList.add(arrayOne[i]);
}
}else{
couchBasePathList.add(path);
}
return couchBasePathList;
}


public static List<Map<String,Object>> queryCouchBase(String sqlKey,String bucketName){
Bucket bucket = null;
try {
if(bucketName.contains(",")){
String[] arrayTwo = bucketName.split("\\,");
if(arrayTwo.length != 2){
AppLogUtils.error("配置文件有误!");
throw new AppException(ErrorCodes.UNKNOWN, "配置文件有误!");
}
bucket = bucketMap.get(arrayTwo[0]);
}else{
bucket = bucketMap.get(bucketName);
}
List<Map<String,Object>> mapList = getMapList(sqlKey,bucket);
return mapList;
} catch (Exception e) {
AppLogUtils.error("连接Couchbase异常!", e.getMessage());
throw new AppException(ErrorCodes.UNKNOWN, "连接Couchbase异常!");
}

}
public static String getBucketName(String temp){
if(temp.contains(",")){
String[] arrayTwo = temp.split("\\,");
if(arrayTwo.length != 2){
AppLogUtils.error("配置文件有误!");
throw new AppException(ErrorCodes.UNKNOWN, "配置文件有误!");
}
return arrayTwo[0];
}else{
return temp;
}
}

public static String getBucketPwd(String temp){
if(temp.contains(",")){
String[] arrayTwo = temp.split("\\,");
if(arrayTwo.length != 2){
AppLogUtils.error("配置文件有误!");
throw new AppException(ErrorCodes.UNKNOWN, "配置文件有误!");
}
return arrayTwo[1];
}else{
return temp;
}
}

//下边这段代码是根据sql语句从桶中查询信息,并转换成mapList返回。
public static List<Map<String,Object>> getMapList(String sqlKey,Bucket bucket){
List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
N1qlQueryResult result = bucket.query(N1qlQuery.simple(sqlKey));
Iterator<N1qlQueryRow> iterator = result.iterator();
while (iterator.hasNext()) {
N1qlQueryRow n1qlQueryRow = iterator.next();
JsonObject jsonObject = n1qlQueryRow.value();
Set<String> set = jsonObject.getNames();
Iterator<String> iterator1 = set.iterator();
Map<String,Object> map = new HashMap<String, Object>();
while (iterator1.hasNext()) {
String key = iterator1.next();
Object object = jsonObject.get(key);
if(object instanceof JsonArray) {
JsonArray value = (JsonArray) object;
List<Object> list1 = new ArrayList<Object>();
for(int i=0;i<value.size();i++) {
Object obj = value.get(i);
if(obj instanceof JsonObject) {
JsonObject jsonObject1 = (JsonObject) obj;
list1.add(jsonObject1.toMap());
} else {
list1.add(value.getString(i));
}
}
map.put(key,list1);
} else if(object instanceof JsonObject) {
JsonObject value = (JsonObject) object;
Map map1 = value.toMap();
map.put(key,map1);
} else {
map.put(key,object);
}
}
mapList.add(map);
}
return mapList;
}
}


第二种方法

public class AppServerCouchBaseClientUtils {
private static String appServerCouchBaseClientPath;
private static Map<String,CouchbaseClient> appServerBucketClientMap = new HashMap<String, CouchbaseClient>();
private static List<URI> uris = new LinkedList<URI>();
private static CouchbaseClient appServerCouchbaseClient;
private static Cluster appServerClientCluster;
private static Map<String,Bucket> appServerClientBucketMap = new HashMap<String, Bucket>();
private static List<String> appServerCouchBaseClientPathList = new ArrayList<String>();
static{
appServerCouchBaseClientPath = APPPropertisUtils.getProperty("appServer.couchbase.path");
}

//初始化化缓存相关配置,外部必须显示调用此方法
public static void init() {
try{
appServerClientCluster = CouchbaseCluster.create(getCouchBaseClientPathList(appServerCouchBaseClientPath));
appServerClientBucketMap.put(getBucketName(APPPropertisUtils.getProperty("appServer.couchbase.bucketname")),openBucket(getBucketName(APPPropertisUtils.getProperty("appServer.couchbase.bucketname")),getBucketPwd(APPPropertisUtils.getProperty("appServer.couchbase.bucketname"))));
appServerCouchbaseClient = new CouchbaseClient(getCouchBasePathList(appServerCouchBaseClientPath),getBucketName(APPPropertisUtils.getProperty("appServer.couchbase.bucketname")),getBucketPwd(APPPropertisUtils.getProperty("appServer.couchbase.bucketname")));
appServerBucketClientMap.put(getBucketName(APPPropertisUtils.getProperty("appServer.couchbase.bucketname")),appServerCouchbaseClient);
}catch (IOException ex){
AppLogUtils.error(ex.getMessage(),"创建couchbaseClient失败!");
throw new AppException(ErrorCodes.UNKNOWN, "创建couchbaseClient失败!");
}
AppLogUtils.info("appServer缓存服务器连接成功...");
}
/**
* 打开桶
* @param bucketName 桶名
* @param password 密码
* @return
*/
private static Bucket openBucket(String bucketName,String password) {
if(StringUtils.isEmpty(password)) {
return appServerClientCluster.openBucket(bucketName,30,TimeUnit.SECONDS);
} else {
return appServerClientCluster.openBucket(bucketName,password,30,TimeUnit.SECONDS);
}
}

public static List<String> getCouchBaseClientPathList(String path){
if(null != appServerCouchBaseClientPathList&&appServerCouchBaseClientPathList.size() > 0){
appServerCouchBaseClientPathList.removeAll(appServerCouchBaseClientPathList);
}
if(path.contains(",")){
String[] arrayOne = path.split("\\,");
for(int i = 0;i < arrayOne.length;i++){
appServerCouchBaseClientPathList.add(arrayOne[i]);
}
}else{
appServerCouchBaseClientPathList.add(path);
}
return appServerCouchBaseClientPathList;
}


public static List<URI> getCouchBasePathList(String path){
if(null != uris&&uris.size() > 0){
uris.removeAll(uris);
}
if(path.contains(",")){
String[] arrayOne = path.split("\\,");
for(int i = 0;i < arrayOne.length;i++){
uris.add(URI.create(arrayOne[i]));
}
}else{
uris.add(URI.create(path));
}
return uris;
}

//获取桶名称
public static String getBucketName(String temp){
if(temp.contains(",")){
String[] arrayTwo = temp.split("\\,");
if(arrayTwo.length != 2){
AppLogUtils.error("配置文件有误!");
throw new AppException(ErrorCodes.UNKNOWN, "配置文件有误!");
}
return arrayTwo[0];
}else{
return temp;
}
}

//获取桶密码
public static String getBucketPwd(String temp){
if(temp.contains(",")){
String[] arrayTwo = temp.split("\\,");
if(arrayTwo.length != 2){
AppLogUtils.error("配置文件有误!");
throw new AppException(ErrorCodes.UNKNOWN, "配置文件有误!");
}
return arrayTwo[1];
}else{
return temp;
}
}


public static CouchbaseClient getCouchBaseClient(){
CouchbaseClient couchbaseClient = null;
try {
String bucketTemp = APPPropertisUtils.getProperty("ppServer.couchbase.bucketname");
if(bucketTemp.contains(",")){
String[] arrayTwo = bucketTemp.split("\\,");
if(arrayTwo.length != 2){
AppLogUtils.error("配置文件有误!");
throw new AppException(ErrorCodes.UNKNOWN, "配置文件有误!");
}
couchbaseClient = AppServerCouchBaseClientUtils.appServerBucketClientMap.get(arrayTwo[0]);
}else{
couchbaseClient = AppServerCouchBaseClientUtils.appServerBucketClientMap.get(bucketTemp);
}
return couchbaseClient;
} catch (Exception e) {
AppLogUtils.error("连接Couchbase异常!", e.getMessage());
throw new AppException(ErrorCodes.UNKNOWN, "连接Couchbase异常!");
}

}

public static List<Map<String,Object>> queryCouchBase(String sqlKey){
Bucket bucket = null;
try {
String bucketTemp = APPPropertisUtils.getProperty("appServer.couchbase.bucketname");
if(bucketTemp.contains(",")){
String[] arrayTwo = bucketTemp.split("\\,");
if(arrayTwo.length != 2){
AppLogUtils.error("配置文件有误!");
throw new AppException(ErrorCodes.UNKNOWN, "配置文件有误!");
}
bucket = AppServerCouchBaseClientUtils.appServerClientBucketMap.get(arrayTwo[0]);
}else{
bucket = AppServerCouchBaseClientUtils.appServerClientBucketMap.get(bucketTemp);
}
List<Map<String,Object>> mapList = getMapList(sqlKey, bucket);
return mapList;
} catch (Exception e) {
AppLogUtils.error("连接Couchbase异常!", e.getMessage());
throw new AppException(ErrorCodes.UNKNOWN, "连接Couchbase异常!");
}

}

/**
* 新增或修改缓存数据(对象)
* @param documentId
* @param jsonObject
* @param outTime 单位为秒
*/
public static void addOrUpdateObjectData(String documentId,int outTime,JsonObject jsonObject) {
CouchbaseClient couchbaseClient = getCouchBaseClient();
couchbaseClient.set(documentId, outTime, jsonObject);
AppLogUtils.info("新增或更新[doucumentId=" + documentId + "]缓存数据成功");
}
/**
* 新增或修改缓存数据(对象),默认失效时间为一天
* @param documentId
* @param jsonObject
*/
public static void addOrUpdateObjectData(String documentId,JsonObject jsonObject) {
CouchbaseClient couchbaseClient = getCouchBaseClient();
couchbaseClient.set(documentId, 24 * 60 * 60, jsonObject);
AppLogUtils.info("新增或更新[doucumentId=" + documentId + "]缓存数据成功");
}

/**
* 批量新增或修改缓存数据(集合对象)
* @param documentIds documentid集合
* @param jsonObject 数据集合
*/
public static void addOrUpdateObjectData(List<String> documentIds,int outTime,List<JsonObject> jsonObject) {
CouchbaseClient couchbaseClient = getCouchBaseClient();
for(int i=0;i<documentIds.size();i++) {
String documentId = documentIds.get(i);
JsonObject temp = jsonObject.get(i);
couchbaseClient.set(documentId, outTime, temp);
AppLogUtils.info("批量新增或修改缓存数据,当前进度为:["+((Float.valueOf(i) / documentIds.size()) * 100)+"%]");
}
}

/**
* 根据doucumentId获取数据
* @param documentId
* @return
*/
public static JsonObject getDataByDocumentId(String documentId) {
if(StringUtils.isEmpty(documentId)) {
return null;
}
CouchbaseClient couchbaseClient = getCouchBaseClient();
JsonObject jsonObject = (JsonObject)couchbaseClient.get(documentId);
return jsonObject;
}


/**
* 根据doucumentId删除数据,单个删除
* @param documentId
* @return
*/
public static void removeDataByDocumentId(String documentId) {
CouchbaseClient couchbaseClient = getCouchBaseClient();
String bucketName = APPPropertisUtils.getProperty("appServer.couchbase.bucketname");
try {
couchbaseClient.delete(documentId);
} catch (Exception e) {
AppLogUtils.error("从bucket="+bucketName+"中移除documentId="+documentId+"失败",e);
}
AppLogUtils.info("删除[doucumentId=" + documentId + "]缓存数据成功");
}

/**
* 根据doucumentId删除数据,批量删除
* @param documentIds
* @return
*/
public static void removeDataByDocumentId(List<String> documentIds) {
CouchbaseClient couchbaseClient = getCouchBaseClient();
String bucketName = APPPropertisUtils.getProperty("appServer.couchbase.bucketname");
for(String documentId : documentIds) {
try {
couchbaseClient.delete(documentId);
} catch (Exception e) {
AppLogUtils.error("从bucket="+bucketName+"中移除documentId="+documentId+"失败",e);
}
}
}


/**
* 通过n1ql查询语句获取数据
* @return
*/
public static List<Map<String,Object>> getMapList(String sqlKey,Bucket bucket){
List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
N1qlQueryResult result = bucket.query(N1qlQuery.simple(sqlKey));
Iterator<N1qlQueryRow> iterator = result.iterator();
while (iterator.hasNext()) {
N1qlQueryRow n1qlQueryRow = iterator.next();
JsonObject jsonObject = n1qlQueryRow.value();
Set<String> set = jsonObject.getNames();
Iterator<String> iterator1 = set.iterator();
Map<String,Object> map = new HashMap<String, Object>();
while (iterator1.hasNext()) {
String key = iterator1.next();
Object object = jsonObject.get(key);
if(object instanceof JsonArray) {
JsonArray value = (JsonArray) object;
List<Object> list1 = new ArrayList<Object>();
for(int i=0;i<value.size();i++) {
Object obj = value.get(i);
if(obj instanceof JsonObject) {
JsonObject jsonObject1 = (JsonObject) obj;
list1.add(jsonObject1.toMap());
} else {
list1.add(value.getString(i));
}
}
map.put(key,list1);
} else if(object instanceof JsonObject) {
JsonObject value = (JsonObject) object;
Map map1 = value.toMap();
map.put(key,map1);
} else {
map.put(key,object);
}
}
mapList.add(map);
}
return mapList;
}
}


第二种相当于创建了一个工具类,便于向couchbase中设置、获取、删除数据,设置时还可以设置此数据的失效时间,相当方便。
在代码中使用了很多类似于APPPropertisUtils.getProperty("appServer.couchbase.bucketname");的代码,这段代码的作用是从配置文件中读取数据,这个可以根据个人喜好,来进行配置。
couchBase.Server.path=http://XXX.XXX.XXX.XXX:8091,http://YYY.YYY.YYY.YYY:8091,http://MMM.MMM.MMM.MMM:8091
couchbase配置地址,多个地址用逗号分隔(这个不是规范,是我自己这么设置的),程序里会进行相应的分隔,用来支持couchbase集群
couchBase.website_company=bucketName,password//这个是桶名称以及桶密码的配置(密码可以不设,这种配置方式并不是规范,是我自己为了方便如此设置,也可以单独配置桶名和密码,希望这点不要迷惑到别人)
couchBase.queryProductList.sql=select * from `表名` //这个是sql语句的配置,表名会在程序里被替换

相关文章