java ElasticSearch并发操作之乐观锁的使用

参考文章:

java ElasticSearch并发操作之乐观锁的使用

简介

        ES在添加和更新操作,其实是不安全的,所有的数据库db系统都会存在并发问题像关系型数据库MySQL,Oracle,SQL Server默认采用的是悲观锁。

     在ElasticSearch中采用的乐观锁,下面先熟悉下什么是乐观锁和悲观锁:

悲观锁(Pessimistic Lock), 顾名思义,就是很悲观,每次去拿数据的时候都认为别人会修改,所以每次在拿数据的时候都会上锁,这样别人想拿这个数据就会block直到它拿到锁。传统的关系型数据库里边就用到了很多这种锁机制,比如行锁,表锁等,读锁,写锁等,都是在做操作之前先上锁。

乐观锁(Optimistic Lock), 顾名思义,就是很乐观,每次去拿数据的时候都认为别人不会修改,所以不会上锁,但是在更新的时候会判断一下在此期间别人有没有去更新这个数据,可以使用版本号等机制。乐观锁适用于多读的应用类型,这样可以提高吞吐量,像数据库如果提供类似于write_condition机制的其实都是提供的乐观锁。

两种锁各有优缺点,不可认为一种好于另一种,像乐观锁适用于写比较少的情况下,即冲突真的很少发生的时候,这样可以省去了锁的开销,加大了系统的整个吞吐量。但如果经常产生冲突,上层应用会不断的进行retry,这样反倒是降低了性能,所以这种情况下用悲观锁就比较合适。

从上面的介绍中,我们不难发现es为什么要采用乐观锁,因为es大部分场景下都是一个读多写少的系统,如果按照悲观锁的策略,会大大降低es的吞吐,当然并发问题是真实存在

在java中插入中使用setCreate(true)方法,标记同一个时刻插入的数据,只会有一条数据插入成功, 在修改中,可以通过es内部维护的version字段来自定义实现灵活控制的乐观锁

java代码如下

/**
 * ES新增或修改同步方法
 *
 * @param index 索引
 * @param type  类型
 * @param id 文档
 * @param json 文档内容
 * @param thread 线程名称
 * @return
 */
public static Map<String, Object> sync(String index, String type, String id, 
                                                 JSONObject json, String thread){
    GetResponse getResponse = get(index, type, id);
    Map map = getResponse.getSource();
    // 不存在
    if(null == map){
        // 新增
        try {
            // get() == execute().actionGet(); 新版本把execute().actionGet() 封装成get().
            // IndexResponse response = client.prepareIndex(index, type, 
            //         id).setCreate(true).setSource(json).execute().actionGet();
            IndexResponse response = client.prepareIndex(index, type, 
                       id).setCreate(true).setSource(json).get();
 
            LOGGER.info(thread + "新增文档成功,文档id为:" + response.getId() + ",
                                 状态为:" + response.status());
        } catch (VersionConflictEngineException e) {
            //e.printStackTrace();
            LOGGER.info(thread + "插入失败" );
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                //e1.printStackTrace();
            }
            sync(index, type, id, json, thread);
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    } else {
        //修改
        try{
            long version = getResponse.getVersion();
            LOGGER.info("此时在修改中,当前版本:" + String.valueOf(version));
 
            // client.prepareUpdate(index, type, id).setDoc(json).setVersion(version)
            //          .execute().actionGet();
            client.prepareUpdate(index, type, id).setDoc(json).setVersion(version).get();
 
            Thread.sleep(100);
            GetResponse response = get(index, type, id);
            Map<String, Object> m = response.getSource();
 
            LOGGER.info(thread + "线程修改完成, 当前年龄为:"+m.get("age") );
 
        } catch (VersionConflictEngineException e) {
            //e.printStackTrace();
            LOGGER.info(thread + "修改失败,当前有线程在修改,休眠1秒后重试...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            sync(index, type, id, json, thread);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    Map map1 = json.getInnerMap();
    return map1;
}
 
/**
 * ES新增同步方法
 * @param index
 * @param type
 * @param id
 * @param json
 * @param thread
 */
public static void  insert(String index, String type, String id, JSONObject json, 
               String thread)  {
    try {
        // IndexResponse response = client.prepareIndex(index, type, 
        //                id).setCreate(true).setSource(json).execute().actionGet();
        IndexResponse response = client.prepareIndex(index, type, 
                        id).setCreate(true).setSource(json).get();
        LOGGER.info(thread + "新增文档成功,文档id为:" + response.getId() 
                                             + ",状态为:" + response.status());
    } catch (VersionConflictEngineException e) {
        LOGGER.info("VersionConflictEngineException =================");
        e.printStackTrace();
        //update(index, type, id, json, thread);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
/**
 * ES修改同步方法
 *
 * @param index
 * @param type
 * @param id
 * @param json
 * @param thread
 */
public static void update(String index, String type, String id, JSONObject json,
                 String thread){
    try{
        // 修改
        GetResponse response = get(index, type, id);
        long version = response.getVersion();
        LOGGER.info("此时在修改中,当前版本:" + String.valueOf(version));
 
        // client.prepareUpdate(index, type, id).setDoc(json).setVersion(version)
        //                                                  .execute().actionGet();
        client.prepareUpdate(index, type, id).setDoc(json).setVersion(version).get();
 
        Thread.sleep(100);
        response = get(index, type, id);
        Map<String, Object> m = response.getSourceAsMap();
 
        LOGGER.info(thread + "线程修改完成, 当前年龄为:"+m.get("age") );
 
    } catch (VersionConflictEngineException e) {
        e.printStackTrace();
        LOGGER.info(thread + "修改失败,当前有线程在修改,休眠3秒后重试...");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        update(index, type, id, json, thread);
    } catch (Exception e) {
        e.printStackTrace();
    }
 
}
 
/**
 * 查询当前的记录
 *
 * @param index
 * @param type
 * @param id
 * @return
 */
public static GetResponse get(String index, String type, String id){
    GetRequestBuilder getRequestBuilder = client.prepareGet(index, type, id);
    GetResponse getResponse = getRequestBuilder.execute().actionGet();
    LOGGER.info("查询当前文档版本为:" + String.valueOf(getResponse.getVersion()));
 
    return getResponse;
}

转载于:https://blog.csdn.net/justlpf/article/details/88057295

原文地址:https://www.cnblogs.com/it-deepinmind/p/14528003.html