You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过负载均衡器将Spring Boot API连接到Elasticsearch

如何通过负载均衡器配置Spring Boot连接Elasticsearch?

Hey there! Since you're new to Spring Boot and Elasticsearch, let's break this down step by step to get your setup working with the load balancer.

先理清几个关键前提:

  • Elasticsearch 默认用 9200 作为HTTP端口(供现代Rest客户端使用),9300 作为TCP端口(旧版TransportClient专用,现已废弃)。负载均衡器通常转发HTTP流量,所以我们重点使用9200端口。
  • 你的负载均衡器需要身份认证,所以我们要在配置中加入对应的用户名和密码。

步骤1:更新application.yml配置

这里分两种常见场景,你可以根据自己的Spring Boot版本选择:

场景1:使用Spring Boot官方推荐的Rest客户端配置(Spring Boot 2.3+)

这是最推荐的方式,适配最新的Elasticsearch RestHighLevelClient:

# 保留你自定义的ES索引配置(如果业务需要)
elasticsearch:
  index: iom

# Spring Boot Elasticsearch Rest客户端核心配置
spring:
  elasticsearch:
    rest:
      uris: http://loadbalancer.test.com:9200
      username: user
      password: pass

场景2:保留原有配置结构(适配旧版自定义配置逻辑)

如果你的代码是基于原有elasticsearch.*配置项读取的,可以这样修改:

# ELASTICSEARCH
elasticsearch:
  index: iom
  clusterName: ElasticsearchCluster # 注意:Rest客户端不需要集群名称,可直接移除
  host: loadbalancer.test.com
  httpPort: 9200 # 替换为负载均衡器的HTTP端口
  # tcpPort: 9200 # 移除该项,我们不再使用废弃的TCP客户端
  username: user
  password: pass

步骤2:确认依赖(若未引入)

如果你的项目还没添加Spring Boot的Elasticsearch starter,在pom.xml(Maven)中加入:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

或者build.gradle(Gradle):

implementation 'org.springframework.boot:spring-boot-starter-data-elasticsearch'

重要注意事项

  1. 废弃的TransportClient:如果你之前用的是通过9300端口连接的TransportClient,强烈建议迁移到RestHighLevelClient——TransportClient在Elasticsearch 7.x中已标记为废弃,8.x版本已完全移除。
  2. 负载均衡器健康检查:确保你的负载均衡器配置了正确的健康检查端点,比如http://loadbalancer.test.com:9200/_cluster/health,这样它能自动剔除不可用的ES节点。
  3. 权限验证:确认负载均衡器的用户名和密码拥有足够的Elasticsearch权限(比如目标索引的读写权限)。

内容的提问来源于stack exchange,提问作者saeedj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:30:18