ElasticSearch学习笔记(八)SpringBoot整合ElasticSearch

Open 这个 分享 由 lemontea 发布于 2017-11-01 · 2230 阅读 0 回复
lemontea 评论于 2017-11-01

这里以gradle工程为例,springboot里面整合es只要导入elasticsearch core和client包就课程了。
build.gradle配置如下:

buildscript {
    repositories {
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath "org.springframework.boot:spring-boot-gradle-plugin:1.5.2.RELEASE"
    }
}
apply plugin: "java"
apply plugin: "org.springframework.boot"

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

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile group: 'org.elasticsearch', name: 'elasticsearch', version: '5.6.3'
    compile group: 'org.elasticsearch.client', name: 'transport', version: '5.6.3'
}

然后在Java代码中配置一个TransportClient的Bean就可以了。代码如下:
EsConfig.java

@Configuration
public class EsConfig {

    @Bean
    public TransportClient client() throws UnknownHostException {
        InetSocketTransportAddress node = new InetSocketTransportAddress(
                InetAddress.getByName("localhost"),
                9300);
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY);
        client.addTransportAddress(node);
        return client;
    }
}

现在就可以愉快的调用es接口了,这里以根据ID查询为例:

@Autowired
private TransportClient client;

@GetMapping("/get/book/novel")
@ResponseBody
public ResponseEntity get(@RequestParam(name = "id", defaultValue = "") String id) {
    if (StringUtils.isEmpty(id)) {
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }
    GetResponse result = this.client.prepareGet("book", "novel", id)
            .get();
    if (!result.isExists()) {
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity(result.getSource(), HttpStatus.OK);
}

本篇涉及到的所有代码可以从这里下载/克隆:https://gitee.com/dev-tang/sbes.git