本地Elasticsearch客户端连接异常求助:连接拒绝与超时
安卓应用连接本地Elasticsearch失败排查求助
我用Kotlin开发安卓应用,尝试连接本地运行的Elasticsearch时遇到两类连接问题:
- 使用
localhost连接时,报错java.net.connectException: connection refused - 使用IP地址(如
192.167.208.131)连接时,出现超时错误
分别用低级别REST客户端和Java API客户端做了测试,代码如下:
低级别REST客户端代码
private fun sendFileStandard() { val restClient = RestClient.builder( HttpHost("192.167.208.131", 9200, "http"), HttpHost("localhost", 9200, "http") ).build() val request = Request( "GET", "/" ) var risultato = "defualt value" doAsync { val cancellable: Cancellable = restClient.performRequestAsync(request, object : ResponseListener { override fun onSuccess(response: Response) { dii("onsuccess", response) risultato = "success" +response.toString() } override fun onFailure(exception: Exception) { dii("onfailure", exception) risultato = "exception" + exception.toString() } }) } dii("risultato", risultato) Thread.sleep(9000) restClient.close(); }
Java API客户端代码
val restClient = RestClient.builder( HttpHost("localhost", 9200) ).build() val transport: ElasticsearchTransport = RestClientTransport( restClient, JacksonJsonpMapper() ) val client = ElasticsearchClient(transport) val input: Reader = StringReader( "{'@timestamp': '2022-04-08T13:55:32Z', 'level': 'warn', 'message': 'Some log message'}" .replace('\'', '"') ) val request = IndexRequest.of { i: IndexRequest.Builder<JsonData?> -> i .index("logs") .withJson(input) } doAsync { val response: IndexResponse = client.index(request) }
排查与解决方案
1. 安卓模拟器访问本地服务的特殊处理
安卓模拟器内的localhost指向模拟器自身,而非你的电脑主机。根据模拟器类型替换地址:
- Android Studio模拟器:用
10.0.2.2代替localhost,这是模拟器预留的主机回环地址 - Genymotion模拟器:用
10.0.3.2代替localhost
2. 修改Elasticsearch绑定地址
默认Elasticsearch仅绑定localhost,外部设备无法访问。修改elasticsearch.yml配置文件:
- 设置
network.host: 0.0.0.0(允许所有地址访问)或你的主机实际IP - 确认
http.port: 9200保持默认配置 - 修改后重启Elasticsearch服务
3. 检查主机防火墙规则
- 临时关闭电脑防火墙,测试是否能连接,排查端口拦截问题
- 若测试通过,在防火墙中添加允许9200端口入站的规则(Windows在高级设置中配置,Linux/macOS用
ufw/iptables设置)
4. 真机测试的网络要求
如果用物理安卓设备测试,需确保设备与运行Elasticsearch的电脑处于同一局域网,且设备能ping通主机IP
5. 代码逻辑修正
- 原代码中
Thread.sleep(9000)是不可靠的异步等待方式,建议将restClient.close()移至回调内,避免提前关闭客户端:
override fun onSuccess(response: Response) { dii("onsuccess", response) risultato = "success" +response.toString() restClient.close() } override fun onFailure(exception: Exception) { dii("onfailure", exception) risultato = "exception" + exception.toString() restClient.close() }
6. 基础连通性验证
- 先在电脑浏览器访问
http://你的主机IP:9200,确认Elasticsearch正常返回JSON响应 - 在安卓设备/模拟器的浏览器中访问同一地址,验证网络层面是否连通
内容的提问来源于stack exchange,提问作者SCORPIOGA3T
相关产品推荐
相关产品推荐

