elasticsearch设置密码访问

1.打开config/elasticsearch.yml,添加以下内容,保存并重启elasticsearch

http.cors.enabled: true

http.cors.allow-origin: "*"

http.cors.allow-headers: Authorization

xpack.security.enabled: true

#xpack.security.transport.ssl.enabled: true

discovery.type: single-node

action.destructive_requires_name: true

2.执行 ./elasticsearch-setup-passwords interactive,指令交互过程中,会让设置4个用户的密码,设置完即可。

3. springboot配置application.yml,添加如下内容,保存

elasticsearch:

  cluster-nodes: xx.xx.xx.xxx(服务器地址)

  cluster-name: 对应你的cluster-name

  cluster-password: elastic:elastic(es设置好的账号密码,格式账号:密码)

4. 添加maven

    org.springframework.boot

    spring-boot-starter-data-elasticsearch

    2.2.6.RELEASE

    org.elasticsearch

    elasticsearch

    6.8.10

    org.elasticsearch.plugin

    transport-netty4-client

    6.8.10

    org.elasticsearch.client

    transport

    6.8.10

    org.elasticsearch.client

    x-pack-transport

    6.8.11

5. 增加ElasticsearchConfig类

@Slf4j

@Configuration

@ConfigurationProperties(prefix = "elasticsearch")

@Data

public class ElasticsearchConfig {

    private String clusterName;

    private String clusterNodes;

    private String clusterPassword;

    @Bean

    public Client client() throws Exception {

        Settings esSettings = Settings.builder()

                .put("cluster.name", clusterName)

                .put("xpack.security.user", clusterPassword)

                .put("xpack.security.transport.ssl.enabled", false)

                //增加嗅探机制,找到ES集群,非集群置为false

                .put("client.transport.sniff", false)

                //增加线程池个数

                .put("thread_pool.search.size", 20)

                .build();

        return new PreBuiltXPackTransportClient(esSettings).addTransportAddress(new TransportAddress(InetAddress.getByName(clusterNodes.substring(0, clusterNodes.indexOf(":"))), 9300));

    }

    @Bean(name = "elasticsearchTemplate")

    public ElasticsearchOperations elasticsearchTemplateCustom() throws Exception {

        ElasticsearchTemplate elasticsearchTemplate;

        try {

            elasticsearchTemplate = new ElasticsearchTemplate(client());

            log.info("初始化ElasticsearchTemplate成功");

            return elasticsearchTemplate;

        } catch (Exception e) {

            e.printStackTrace();

            log.error("初始化ElasticsearchTemplate失败");

            return new ElasticsearchTemplate(client());

        }

    }

}

你可能感兴趣的:(elasticsearch设置密码访问)