springboot2.2.7集成elasticsearch7.6.2 gradle插件环境

这几天一直都在尝试,当然也浏览了大量博主的帖子,最后都失败了。

直到发现了这位珍宝博主,阿门!!原来并不是所有人都会写通俗易懂的博客。。。

 

废话说完了,现在开始集成:

1 下载ES7.6.2版本 https://www.elastic.co/cn/downloads/past-releases#elasticsearch ,解压后打开config\elasticsearch.yml并添加配置:

# 解决启动失败问题
xpack.ml.enabled: false
# 解决head插件连接
http.cors.enabled: true
http.cors.allow-origin: "*"

2 下载ik分词 https://github.com/medcl/elasticsearch-analysis-ik/releases,解压后复制到es的plugins文件夹下并改名 analysis-ik

3 下载head插件 https://github.com/mobz/elasticsearch-head,解压后使用cmd在es-head文件夹下运行 npm run start,如果 没有npm、nodejs环境的需要去安装

4 (可不安装)下载cerebro https://github.com/lmenezes/cerebro/releases,解压后使用cmd在bin目录中运行 cerebro.bat

5 初始化springboot2.2.7环境

    5-1 配置EsConfig

@Component
@PropertySource("classpath:application.yml")    //配置文件地址,可以自定义
@ConfigurationProperties("elasticsearch")       //属性前缀
public class ElasticSearchClientConfig {
    //    @Value("${elasticsearch.hostList}")
    private String hostList;//配置文件中的属性

    public String getHostList() {
        return hostList;
    }

    public void setHostList(String hostList) {
        this.hostList = hostList;
    }

    @Bean(value = "RestHighLevelClient", destroyMethod = "close")
    public RestHighLevelClient restHighLevelClient() {
        //通过逗号分割节点
        String[] split = hostList.split(",");
        HttpHost[] httpHosts = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++) {
            //通过冒号分离出每一个节点的ip,port
            String[] split1 = split[i].split(":");
            //这里http写固定了,只为测试使用,可以通过读取配置文件赋值的方式优化
            httpHosts[i] = new HttpHost(split1[0], Integer.parseInt(split1[1]), "http");
        }
        return new RestHighLevelClient(RestClient.builder(httpHosts));
    }
}

    5-2 application.yml配置

elasticsearch:
  hostList: localhost:9200 #多个节点用逗号隔开

    5-3 build.gradle配置

plugins {
    id 'org.springframework.boot' version '2.2.7.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    maven { url "http://maven.aliyun.com/nexus/content/groups/public" }
}

dependencies {
    compile 'org.projectlombok:lombok'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    implementation 'org.springframework.boot:spring-boot-starter'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.2.7.RELEASE'
// https://mvnrepository.com/artifact/com.alibaba/fastjson
    compile group: 'com.alibaba', name: 'fastjson', version: '1.2.68'


    // https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client
    compile group: 'org.elasticsearch.client', name: 'elasticsearch-rest-high-level-client', version: '7.6.2'
    // https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch
    compile group: 'org.elasticsearch', name: 'elasticsearch', version: '7.6.2'
    // https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-client
    compile group: 'org.elasticsearch.client', name: 'elasticsearch-rest-client', version: '7.6.2'



}

test {
    useJUnitPlatform()
}

 

    5-4 使用单元测试验证

@Slf4j
@SpringBootTest
class RestHighLevelClientTests {

    @Autowired
    @Qualifier("RestHighLevelClient")
    private RestHighLevelClient client;

  
    /**
     * 添加数据
     * @throws IOException
     */
    @Test
    public void indexAdd() throws IOException {
        UserTest userTest = new UserTest();
        userTest.setName("董28");
        userTest.setSex("男");
        //由于客户端不支持自定义实体对象类作为添加数据的参数,所以提前先将对象转化为Map对象
        String s = JSON.toJSONString(userTest);
        JSONObject json = JSONObject.parseObject(s);
        Map map = json;    
        System.out.println(map);
        IndexRequest indexRequest = new IndexRequest("book")
                .source(map);
        //异步
        client.indexAsync(indexRequest, RequestOptions.DEFAULT, new ActionListener() {

            @Override
            public void onResponse(IndexResponse indexResponse) {
                System.out.println(indexResponse);
                if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
                    //新建
                } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
                    //修改
                }
                ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
                if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
                    //
                }
                if (shardInfo.getFailed() > 0) {
                    for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
                        String reason = failure.reason();
                    }
                }

            }

            @Override
            public void onFailure(Exception e) {
                System.out.println("exception...");
            }
        });
  
    }


    /**
     * 通过索引index,id查询
     *
     */
    @Test
    public void get1() throws IOException {
        GetRequest getRequest = new GetRequest("posts", "0DSIHnIBkMTi7Cf1XtQr");
        /*FetchSourceContext fetchSourceContext = new FetchSourceContext(true, new String[]{"sex"}, Strings.EMPTY_ARRAY);
        getRequest.fetchSourceContext(fetchSourceContext)*/
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        if (getResponse.isExists()) {
            log.info("getResponse[{}]", getResponse);
            log.info("getResponse.getId()[{}]", getResponse.getId());
            log.info("getResponse.getSource()[{}]", getResponse.getSource());
            log.info("getResponse.getSourceAsString()[{}]", getResponse.getSourceAsString());
            log.info("getResponse.getSourceAsMap()[{}]", getResponse.getSourceAsMap());

            UserTest userTest1 = JSONObject.parseObject(getResponse.getSourceAsString(), UserTest.class);
            log.info("userTest1[{}]", userTest1);

            String jsonString = JSON.toJSONString(getResponse.getSource());
            UserTest userTest2 = JSONObject.parseObject(jsonString, UserTest.class);
            log.info("userTest2[{}]", userTest2);

        }
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class UserTest {
        private int id;
        private String name;
        private String sex;
        private Others others = new Others("[email protected]", "199");
    }

    @Data
    @AllArgsConstructor
    public static class Others {
        private String email;
        private String phone;
    }

}

 

以上单元测试运行后,集成工作就基本完成了。

希望能帮助到大家,深深了解找了很久的文章都失败的沮丧。。。

你可能感兴趣的:(JAVA,es)