springboot项目spring-data-elasticsearch添加x-pack身份认证(elasticsearch6.x)

依赖

注意:依赖版本可能会不兼容,注意根据自己的去适配(本文使用的是es6.6版本)

		<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-elasticsearchartifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch.clientgroupId>
                    <artifactId>transportartifactId>
                exclusion>
            exclusions>
        dependency>
  		<dependency>
            <groupId>org.elasticsearch.clientgroupId>
            <artifactId>x-pack-transportartifactId>
            <version>6.4.3version>
        dependency>
        
        <-- transportClient依赖了log4j -->
        <dependency>
            <groupId>org.apache.logging.log4jgroupId>
            <artifactId>log4j-apiartifactId>
            <version>2.7version>
        dependency>
        <dependency>
            <groupId>org.apache.logging.log4jgroupId>
            <artifactId>log4j-coreartifactId>
            <version>2.7version>
        dependency>

yml配置

elasticSearch:
  host: 127.0.0.1
  port: 9300
  cluster-name: elasticsearch
  user.password: elastic:123456

java配置

注意:需要在类上面加@Configuration注解

    /**
     * es集群读取路径
     */
    public static final String X_PACK_ES_NAME="cluster.name";
    /**
     *x-pack用户名密码读取路径
     */
    public static final String X_PACK_USER="xpack.security.user";

    @Value("${elasticSearch.cluster-name}")
    private String esClusterName;
    @Value("${elasticSearch.host}")
    private String esHost;
    @Value("${elasticSearch.port}")
    private int esPort;
    @Value("${elasticSearch.user.password}")
    private String esUserPassword;

    private final Logger LOGGER = LoggerFactory.getLogger(BeanConfiguration.class);

    /**
     * elasticsearch客户端注入(配置)
     *
     * @return
     * @throws UnknownHostException
     */
    @Bean
    public TransportClient transportClient() throws UnknownHostException {
        TransportClient client = new PreBuiltXPackTransportClient(Settings.builder()
                .put(X_PACK_ES_NAME, esClusterName)
                .put(X_PACK_USER, esUserPassword)
                .build())
                .addTransportAddress(new TransportAddress(InetAddress.getByName(esHost), esPort));
        return client;
    }

然后就可以访问了

你可能感兴趣的:(资源,实现代码)