Меню

Java net sockettimeoutexception read timed out ошибка

I have a Tomcat based web application. I am intermittently getting the following exception,

Caused by: java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:150)
    at java.net.SocketInputStream.read(SocketInputStream.java:121)
    at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:532)
    at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:501)
    at org.apache.coyote.http11.InternalInputBuffer$InputStreamInputBuffer.doRead(InternalInputBuffer.java:563)
    at org.apache.coyote.http11.filters.IdentityInputFilter.doRead(IdentityInputFilter.java:124)
    at org.apache.coyote.http11.AbstractInputBuffer.doRead(AbstractInputBuffer.java:346)
    at org.apache.coyote.Request.doRead(Request.java:422)
    at org.apache.catalina.connector.InputBuffer.realReadBytes(InputBuffer.java:290)
    at org.apache.tomcat.util.buf.ByteChunk.substract(ByteChunk.java:431)
    at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:315)
    at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:200)
    at java.nio.channels.Channels$ReadableByteChannelImpl.read(Channels.java:385)

Unfortunately I don’t have access to the client, so I am just trying to confirm on various reasons this can happen,

  1. Server is trying to read data from the request, but its taking longer than the timeout value for the data to arrive from the client. Timeout here would typically be Tomcat connector → connectionTimeout attribute.

  2. Client has a read timeout set, and server is taking longer than that to respond.

  3. One of the threads I went through, said this can happen with high concurrency and if the keepalive is enabled.

For #1, the initial value I had set was 20 sec, I have bumped this up to 60sec, will test, and see if there are any changes.

Meanwhile, if any of you guys can provide you expert opinion on this, that’l be really helpful. Or for that matter any other reason you can think of which might cause this issue.

double-beep's user avatar

double-beep

4,84016 gold badges32 silver badges41 bronze badges

asked Jun 13, 2013 at 4:30

Victor's user avatar

1

Server is trying to read data from the request, but its taking longer than the timeout value for the data to arrive from the client. Timeout here would typically be tomcat connector -> connectionTimeout attribute.

Correct.

Client has a read timeout set, and server is taking longer than that to respond.

No. That would cause a timeout at the client.

One of the threads i went through, said this can happen with high concurrency and if the keepalive is enabled.

That is obviously guesswork, and completely incorrect. It happens if and only if no data arrives within the timeout. Period. Load and keepalive and concurrency have nothing to do with it whatsoever.

It just means the client isn’t sending. You don’t need to worry about it. Browser clients come and go in all sorts of strange ways.

answered Jun 13, 2013 at 5:45

user207421's user avatar

6

Here are the basic instructions:-

  1. Locate the «server.xml» file in the «conf» folder beneath Tomcat’s base directory (i.e. %CATALINA_HOME%/conf/server.xml).
  2. Open the file in an editor and search for <Connector.
  3. Locate the relevant connector that is timing out — this will typically be the HTTP connector, i.e. the one with protocol="HTTP/1.1".
  4. If a connectionTimeout value is set on the connector, it may need to be increased — e.g. from 20000 milliseconds (= 20 seconds) to 120000 milliseconds (= 2 minutes). If no connectionTimeout property value is set on the connector, the default is 60 seconds — if this is insufficient, the property may need to be added.
  5. Restart Tomcat

answered Sep 19, 2018 at 13:10

Steve Chambers's user avatar

Steve ChambersSteve Chambers

35.4k21 gold badges151 silver badges203 bronze badges

Connection.Response resp = Jsoup.connect(url) //
                .timeout(20000) //
                .method(Connection.Method.GET) //
                .execute();

actually, the error occurs when you have slow internet so try to maximize the timeout time and then your code will definitely work as it works for me.

answered Mar 5, 2019 at 15:09

Rishabh Gupta's user avatar

1

I had the same problem while trying to read the data from the request body. In my case which occurs randomly only to the mobile-based client devices. So I have increased the connectionUploadTimeout to 1min as suggested by this link

answered Dec 4, 2020 at 17:23

Anand Kumar's user avatar

I have the same issue. The java.net.SocketTimeoutException: Read timed out error happens on Tomcat under Mac 11.1, but it works perfectly in Mac 10.13. Same Tomcat folder, same WAR file. Have tried setting timeout values higher, but nothing I do works.
If I run the same SpringBoot code in a regular Java application (outside Tomcat 9.0.41 (tried other versions too), then it works also.

Mac 11.1 appears to be interfering with Tomcat.

As another test, if I copy the WAR file to an AWS EC2 instance, it works fine there too.

Spent several days trying to figure this out, but cannot resolve.

Suggestions very welcome! 🙂

answered Jan 31, 2021 at 13:38

Morkus's user avatar

MorkusMorkus

4876 silver badges18 bronze badges

1

This happenned to my application, actually I was using a single Object which was being called by multiple functions and those were not thread safe.

Something like this :

Class A{
    Object B;
    function1(){
        B.doSomething();
    }
    function2(){
        B.doSomething();
    }
}

As they were not threadsafe, I was getting these errors :

redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Socket is closed

and

redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: Read timed out

This is how I fixed it :

Class A{
    function1(){
        Object B;
        B.doSomething();
    }
    function2(){    
        Object B;
        B.doSomething();
    }
}

Hope it helps

answered Jun 22, 2022 at 10:27

Aditya's user avatar

It means time out from your server response. It causes due to server config and internet response.

answered Mar 20, 2021 at 15:32

jawad zahoor's user avatar

I am using 11.2 and received timeouts.

I resolved by using the version of jsoup below.

    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.7.2</version>
        <scope>compile</scope>
    </dependency>

entpnerd's user avatar

entpnerd

9,6497 gold badges44 silver badges67 bronze badges

answered Feb 7, 2018 at 14:40

Shahid Hussain Abbasi's user avatar

Играя в Minecraft и вообще, пользуясь приложениями, написанными на Java Вы не раз могли столкнуться с ошибками (исключениями). В отличие от других языков программирования, Java жёстко заточена под использование ООП, потому при возникновении ошибки бросается исключение (объект содержащий сведения под ошибке). Его можно «поймать», дабы предпринять какие-то действия (допустим, вывести в лог). В случае майнкрафта, при возникновении исключения, создаётся краш-отчёт и работа игры завершается.

Понять исключения достаточно просто и вам для этого не понадобится специальное ПО для отладки.

2017-10-03_153645.png

Полная печать исключения состоит из 3-х частей:

  1. Исключение — имя класса ошибки. Классам обычно дают понятные человеку имена, достаточно знаний английского, чтобы понять значение.
  2. Сообщение — содержит более детальное описание ошибки. Может отсутствовать.
  3. Стек вызова — отражает ход работы программы (снизу вверх). Данная информация больше полезна разработчику, дабы понять, где именно возникла ошибка. Обычному пользователю данная информация может помочь понять, с чем связана ошибка (по именам классов и вызываемым функциям — методам).

Исключения могут иметь предков, что присутствует в данном примере (после «Caused by» идёт печать исключения-предка). Если вам не понятно исключение, возможно, стоит рассмотреть его предков — они могут содержать более понятное сообщение.

В данной теме я опишу наиболее часто встречающиеся ошибки, а также, какие действия следует или вовсе не следует предпринимать. Причин у ошибок множество и это не всегда повреждённые файлы игры (чего быть в принципе не может, поскольку лаунчер проверяет файлы игры).

При возникновении ошибок не спешите бежать переустанавливать Java и игру! Java — стабильный продукт. В большинстве случаев, ошибки возникают из-за неправильной настройки ОС; ошибок сети; неправильных драйверов.

org.lwjgl.LWJGLException: Pixel format not accelerated
Недоступно аппаратное ускорение графики. Описание ошибки (англ.)

Решение: Установите последнюю версию драйвера видеокарты.

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation/building failed
Не удаётся установить защищённое соединение из-за невозможности проверки SSL сертификата.

Что можно сделать:

  • Эта ошибка может возникнуть из-за использования слишком старой версии Java. Рекомендуется регулярно обновлять ПО, чтобы иметь актуальный список корневых сертификатов.
  • Виновником может быть антивирус, пытающийся «подсунуть» свой сертификат с целью прослушивания трафика. Настоятельно рекомендуется отключить в антивирусе проверку защищённых соединений (HTTPS/SSL/TLS) — это значительно снижает безопасность защищённых соединений и вызывает проблемы в работе приложений, использующие их.

java.net.SocketTimeOutException: Read timed out
Ошибка сети «время ожидания истекло». Здесь сложно установить виновника: проблема может быть как на стороне сервера, вашего провайдера или вызвана антивирусом.

Что можно сделать:

  • Отключите антивирус и попробуйте выполнить запрос снова.
  • Используйте другое подключение к интернету (другой провайдер; мобильный интернет; VPN; Wi-Fi соседей).
  • Используйте VPN для обхода блокировки (цензуры) со стороны вашего интернет-провайдера.

java.net.ConnectException: Connection timed out: connect
Ошибка сети — не удалось установить соединение с хостом. Обычно виновником данной ошибки является Firewall (брандмауэр) или отсутствие интернета.

Что можно сделать:

  • Проверьте наличие подключения к интернету.
  • Временно отключите антивирус и Firewall.

java.net.SocketException: Connection reset / Удаленный хост принудительно разорвал существующее подключение
Ошибка сети «соединение сброшено». Как и в предыдущей ошибке, проблема связана с «плохим» интернетом, либо проблемами на стороне сервера (в этом случае ошибка будет у всех). Чаще всего возникает у пользователей мобильного интернета (USB-модем). От вас никаких действий предпринимать не требуется, кроме как найти «другой интернет» или использовать VPN для обхода фильтра сайтов.

java.lang.ClassCastException: XXX cannot be cast to YYY
Ошибка в логике программы: попытка привести объект к классу, экземпляром коего объект не является.

Решение: Сообщите о проблеме разработчику программы, приложив лог ошибки.

java.io.IOException: Server returned HTTP response code: 000 for URL
Проблема на стороне веб-сервера. Стандартная библиотека Java выбрасывает исключение, если веб-сервер выдаёт, например, страницу «404 Not Found».

Решение: Сообщите о проблеме владельцу веб-сервера, URL которого указан в тексте ошибки.

java.lang.UnsatisfiedLinkError: Can’t load library:
Не удалось загрузить нативную библиотеку (скорее всего, отсутствует файл по указанному пути).

Что можно сделать:

  • Чаще всего ошибка возникает из-за отсутствия библиотек LWJGL. Почему их файлы пропадают, пока остаётся загадкой. Если пути вы видите «.redserver/natives/2.9.1/lwjgl.dll», значит надо удалить папку natives, находящуюся в .redserver, чтобы лаунчер их скачал заново.
    Неактуально: С версии 3.2 лаунчер проверяет наличие всех файлов и автоматически, при необходимости, перекачивает их.

java.lang.RuntimeException: Unknown character in
Синтаксическая ошибка в конфигурационном файле мода.

Что можно сделать:

  • Удалите указанный в ошибке файл. Мод создаст новый с настройками по умолчанию.
  • Если вам сложно удалить файл, можно сделать сброс конфигов через лаунчер. Нажмите в лаунчере на многоточие на кнопке «Играть»; выберите в меню пункт «Очистка клиента»; установите флажок возле «Сбросить конфигурацию» и запустите очистку.
  • Выполните проверку диска на наличие ошибок. Испорченные файлы могут быть признаком неисправности диска.

java.lang.NullPointerException (NPE)
Ошибка в логике программы: попытка вызвать нестатичный метод, обратиться к полю несуществующего объекта — null.

Решение: Сообщите о проблеме разработчику программы, приложив лог ошибки.

java.net.UnknownHostException
Ошибка сети: не удаётся определить IP-адрес доменного имени (в общем, проблемы с DNS).

Что можно сделать:

  • Иногда ошибка может возникать, если вы не подключены к интернету, либо же произошёл разрыв интернет-соединения. Обычно исчезает сама через небольшой промежуток времени после возобновления соединения. Если ошибка не исчезла — может помочь перезагрузка компьютера (сбрасывает кеш DNS).
  • Доступ к ресурсу заблокирован вашим провайдером. Сейчас данная проблема актуальна для украинских пользователей: используемый нами Яндекс.DNS заблокирован в этой стране. Читайте, как обойти блокировку DNS.

java.io.EOFException: Unexpected end of ZLIB input stream
Неожиданный конец файла. В данном случае — ZIP-архива. Возникает например, когда вы пытаетесь распаковать недокачанный архив.

java.net.SocketException: Address family not supported by protocol family: connect
Проблема возникает из-за неправильной настройки протокола IPv6. Если таковой не поддерживается вашим интернет-провайдером, его поддержку следует отключить.

image.png

java.lang.OutOfMemoryError
А вот это как раз «любимая» ошибка про нехватку ОЗУ. Не стоит сразу спешить выставлять память в лаунчере на максимум, потому что дальнейшие действия зависят от сообщения к ошибке:

  • Unable to create new native thread / Metaspace — в вашей системе закончились ресурсы (ОЗУ). Решается только путём завершения всех лишних программ, либо апгрейдом ПК (больше ОЗУ — больше программ можно запустить). Не забывайте, что следует использовать 64-разрядную систему.
  • Java heap space — нехватка размера heap области памяти. Увеличьте лимит памяти в настройках лаунчера.

Platform Notice: Data Center OnlyThis article only applies to Atlassian products on the data center platform.

Summary

When a Jira instance makes an HTTP request to a remote server, the request fails with a message similar to: 

Exception in request: java.net.SocketTimeoutException: Read timed out in http POST to ...

Environment

The issue may occur in any setup where one Jira instance makes an HTTP request to a remote server.

For example, Jira A makes a request to Jira B via the Jira to Jira Issue Copy. 

Diagnosis

The request in the remote server succeeds but takes more than 10 seconds, which is the default socket timeout for the client. 

Cause

The reason why the request in the remote server takes more than 10 seconds should be investigated and potentially fixed. 

If the request legitimately takes more than 10 seconds, the default socket timeout of 10 seconds isn’t enough on the Apache client side. 

Solution

Increase the Apache client socket timeout via the JVM parameter http.socket.timeout

In some cases, we have seen apps that use a different parameter http.socketTimeout.

  • The value needs to be set in milliseconds.
    For example: -Dhttp.socket.timeout=20000.
  • For more details on setting up the JVM parameter, please refer to the Atlassian documentation Setting properties and options on startup.
  • Jira should be restarted for the change to be effective.

Jsoup SocketTimeoutException read timed out, connect timed out example shows how to fix SocketTimeoutException while using Jsoup in Java. The example also shows how to set the timeout in Jsoup.

How to fix Jsoup java.net.SocketTimeoutException: Read timed out exception?

You may encounter “java.net.SocketTimeoutException: Read timed out” exception while using the Jsoup. Here is the program which gave me the exception.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

package com.javacodeexamples.libraries.jsoup;

import java.io.IOException;

import org.jsoup.Connection;

import org.jsoup.Jsoup;

import org.jsoup.nodes.Document;

public class JsoupSocketTimeOutExample {

    public static void main(String[] args) {

        try{

            //connect to the website

            Connection connection = Jsoup.connect(«http://www.example.com»);

            //set user agent to Google Chrome

            connection.userAgent(«Mozilla/5.0»);

            //get the HTML document

            Document doc = connection.get();

            //parse text from HTML

            String strHTML = doc.text();

        }catch(IOException ioe){

            //System.out.println(«IOException: » + ioe);

            ioe.printStackTrace();

        }

    }

}

Output

java.net.SocketTimeoutException: Read timed out

    at java.net.SocketInputStream.socketRead0(Native Method)

    at java.net.SocketInputStream.read(Unknown Source)

    at java.net.SocketInputStream.read(Unknown Source)

    at sun.security.ssl.InputRecord.readFully(Unknown Source)

    …

Fix: 

The problem is the default Jsoup timeout which is 3 seconds. If you encounter the exception “java.net.SocketTimeoutException: Read timed out”, it means that time our program took to read the requested webpage was exceeded the default timeout time (3 seconds).

You need to increase the timeout Jsoup uses to fix the problem using timeout method of Connection class.

Connection timeout(int timeout)

This method sets the connect and read timeout both. Please note that the timeout is in milliseconds.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

try{

    //connect to the website

    Connection connection = Jsoup.connect(«http://www.example.com»);

    //set user agent to Google Chrome

    connection.userAgent(«Mozilla/5.0»);

    //set timeout to 10 seconds

    connection.timeout(10 * 1000);

    //get the HTML document

    Document doc = connection.get();

    //parse text from HTML

    String strHTML = doc.text();

}catch(IOException ioe){

    //System.out.println(«IOException: » + ioe);

    ioe.printStackTrace();

}

How to fix Jsoup java.net.SocketTimeoutException: Connect timed out exception?

Another exception Jsoup may throw is “java.net.SocketTimeoutException: Connect timed out”. This exception means the time taken by our program to connect to the requested URL exceeded the timeout Jsoup uses.

Here is how to fix/resolve the “Connect time out” exception.

1) Make sure you are connected to the internet. Try to open the same URL in the browser and see if it opens the page.
2) Specify Jsoup connection time out before getting the document as given below.

String strText =

        Jsoup

        .connect(«http://www.example.com/»)

        .userAgent(«Mozilla/5.0»)

        .timeout(10 * 1000)

        .get()

        .text();

3) Are you behind the proxy? If yes, set Jsoup proxy.
4) It is always best practice to set user agent and referrer while creating a Jsoup connection.

Many times setting property user agent and referrer values solves this problem.

This example is a part of the Jsoup tutorial with examples.

Please let me know your views in the comments section below.

About the author

  • Author
  • Recent Posts

Rahim

I have a master’s degree in computer science and over 18 years of experience designing and developing Java applications. I have worked with many fortune 500 companies as an eCommerce Architect. Follow me on LinkedIn and Facebook.

We are on YouTube!

The idea is to make the server listening and the clients would connect to them.
But not as a Modbus TCP client, as a normal TCP client, so the server could read the clients (act like Modbus Master) rather than read by clients.
Maybe the idea totally wrong.

The test code:

    @Test
    public void testConnection() throws IOException, ModbusNumberException, ModbusProtocolException, ModbusIOException {
        ServerSocket serverSocket = new ServerSocket(3333);
        Socket client = serverSocket.accept();
        ModbusTranslator modbusTranslator = new ModbusTranslator(client);
        modbusTranslator.connect();
        modbusTranslator.setResponseTimeout(3000);
        modbusTranslator.writeSingleRegister(1,1,1);
    }

Which will issue a SocketTimeoutException when running the test.
Using hercules-setup-utility from https://www.hw-group.com/software/hercules-setup-utility
to simulate a client socket.

  1. The network is fine when using client.getOutputStream() and client.getInputStream();
  2. The error log is almost same if change last line to modbusTranslator.readHoldingRegisters(1,1,1);
  3. The ModbusTranslator implements FrameEventListenerList with a custom EmbeddedConnection which extends ModbusConnection

The mainly different from your ModbusMasterConnection is it get the socket instead from init from tcp parameters.

    @Override
    protected void openImpl() {
        if (!isOpened()) {
            if (socket.isConnected()) {
                try {
                    transport = ModbusTransportFactory.createTCP(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                setReadTimeout(getReadTimeout());
            }
        }
    }
com.intelligt.modbus.jlibmodbus.exception.ModbusIOException: java.net.SocketTimeoutException: Read timed out

	at com.intelligt.modbus.jlibmodbus.tcp.TcpAduHeader.read(TcpAduHeader.java:103)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransportTCP.read(ModbusTransportTCP.java:50)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readMessage(ModbusTransport.java:69)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readResponse(ModbusTransport.java:64)
	at dems.server.ModbusTranslator.readResponse(ModbusTranslator.java:80)
	at dems.server.ModbusTranslator.processRequest(ModbusTranslator.java:100)
	at dems.server.ModbusTranslator.writeSingleRegister(ModbusTranslator.java:264)
	at dems.server.ModbusTranslatorTest.testConnection(ModbusTranslatorTest.java:19)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:564)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.net.SocketTimeoutException: Read timed out
	at java.base/java.net.SocketInputStream.socketRead0(Native Method)
	at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
	at java.base/java.net.SocketInputStream.read(SocketInputStream.java:171)
	at java.base/java.net.SocketInputStream.read(SocketInputStream.java:141)
	at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
	at java.base/java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
	at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:345)
	at com.intelligt.modbus.jlibmodbus.net.stream.InputStreamTCP$1.read(InputStreamTCP.java:55)
	at com.intelligt.modbus.jlibmodbus.net.stream.base.LoggingInputStream.read(LoggingInputStream.java:61)
	at com.intelligt.modbus.jlibmodbus.net.stream.base.ModbusInputStream.read(ModbusInputStream.java:50)
	at com.intelligt.modbus.jlibmodbus.tcp.TcpAduHeader.read(TcpAduHeader.java:91)
	... 29 more

Disconnected from the target VM, address: '127.0.0.1:53170', transport: 'socket'

Process finished with exit code -1

Any help would be appreciated.

1. Purpose

In this post, I would demonstrate how to debug the following error when using feign.

2022-02-18 15:29:38.417 ERROR 44793 --- [nio-8086-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is feign.RetryableException: Read timed out executing GET http://nacos-provider-bswencw1/hello] with root cause

java.net.SocketTimeoutException: Read timed out
        at java.net.SocketInputStream.socketRead0(Native Method) ~[na:1.8.0_121]
        at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) ~[na:1.8.0_121]
        at java.net.SocketInputStream.read(SocketInputStream.java:171) ~[na:1.8.0_121]
        at java.net.SocketInputStream.read(SocketInputStream.java:141) ~[na:1.8.0_121]
        at java.io.BufferedInputStream.fill(BufferedInputStream.java:246) ~[na:1.8.0_121]
        at java.io.BufferedInputStream.read1(BufferedInputStream.java:286) ~[na:1.8.0_121]
        at java.io.BufferedInputStream.read(BufferedInputStream.java:345) ~[na:1.8.0_121]
        at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:704) ~[na:1.8.0_121]
        at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647) ~[na:1.8.0_121]
        at 

2. The solution

2.1 The details of the problem

➜  nacos-feign ./start.sh 8086
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building nacos-feign 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) @ nacos-feign ---
[INFO] 
[INFO] >>> spring-boot-maven-plugin:2.1.18.RELEASE:run (default-cli) > test-compile @ nacos-feign >>>
[INFO] 
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ nacos-feign ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ nacos-feign ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 4 source files to /Users/bswencaiwen/JavaProjects/SpringCloudLearning202202/nacos-feign/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ nacos-feign ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/bswencaiwen/JavaProjects/SpringCloudLearning202202/nacos-feign/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ nacos-feign ---
[INFO] Changes detected - recompiling the module!
[INFO] 
[INFO] <<< spring-boot-maven-plugin:2.1.18.RELEASE:run (default-cli) < test-compile @ nacos-feign <<<
[INFO] 
[INFO] --- spring-boot-maven-plugin:2.1.18.RELEASE:run (default-cli) @ nacos-feign ---

  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |___, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v2.1.18.RELEASE)

2022-02-18 15:28:49.521  INFO 44793 --- [           main] c.e.nacosfeign.NacosFeignApplication     : No active profile set, falling back to default profiles: default
2022-02-18 15:28:52.439  INFO 44793 --- [           main] c.e.nacosfeign.NacosFeignApplication     : Started NacosFeignApplication in 5.934 seconds (JVM running for 10.224)
2022-02-18 15:29:38.417 ERROR 44793 --- [nio-8086-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is feign.RetryableException: Read timed out executing GET http://nacos-provider-bswencw1/hello] with root cause

java.net.SocketTimeoutException: Read timed out
        at java.net.SocketInputStream.socketRead0(Native Method) ~[na:1.8.0_121]
        at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) ~[na:1.8.0_121]
        at java.net.SocketInputStream.read(SocketInputStream.java:171) ~[na:1.8.0_121]
        at java.net.SocketInputStream.read(SocketInputStream.java:141) ~[na:1.8.0_121]
        at java.io.BufferedInputStream.fill(BufferedInputStream.java:246) ~[na:1.8.0_121]
        at java.io.BufferedInputStream.read1(BufferedInputStream.java:286) ~[na:1.8.0_121]
        at java.io.BufferedInputStream.read(BufferedInputStream.java:345) ~[na:1.8.0_121]
        at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:704) ~[na:1.8.0_121]
        at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647) ~[na:1.8.0_121]
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1569) ~[na:1.8.0_121]
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474) ~[na:1.8.0_121]
        at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) ~[na:1.8.0_121]
        at feign.Client$Default.convertResponse(Client.java:82) ~[feign-core-10.4.0.jar:na]
        at feign.Client$Default.execute(Client.java:78) ~[feign-core-10.4.0.jar:na]
        at org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer.execute(FeignLoadBalancer.java:93) ~[spring-cloud-openfeign-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
        at org.springframework.cloud.openfeign.ribbon.FeignLoadBalancer.execute(FeignLoadBalancer.java:56) ~[spring-cloud-openfeign-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
        at com.netflix.client.AbstractLoadBalancerAwareClient$1.call(AbstractLoadBalancerAwareClient.java:104) ~[ribbon-loadbalancer-2.3.0.jar:2.3.0]
        at com.netflix.loadbalancer.reactive.LoadBalancerCommand$3$1.call(LoadBalancerCommand.java:303) ~[ribbon-loadbalancer-2.3.0.jar:2.3.0]
        at com.netflix.loadbalancer.reactive.LoadBalancerCommand$3$1.call(LoadBalancerCommand.java:287) ~[ribbon-loadbalancer-2.3.0.jar:2.3.0]
        at rx.internal.util.ScalarSynchronousObservable$3.call(ScalarSynchronousObservable.java:231) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.util.ScalarSynchronousObservable$3.call(ScalarSynchronousObservable.java:228) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.Observable.unsafeSubscribe(Observable.java:10327) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.operators.OnSubscribeConcatMap$ConcatMapSubscriber.drain(OnSubscribeConcatMap.java:286) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.operators.OnSubscribeConcatMap$ConcatMapSubscriber.onNext(OnSubscribeConcatMap.java:144) ~[rxjava-1.3.8.jar:1.3.8]
        at com.netflix.loadbalancer.reactive.LoadBalancerCommand$1.call(LoadBalancerCommand.java:185) ~[ribbon-loadbalancer-2.3.0.jar:2.3.0]
        at com.netflix.loadbalancer.reactive.LoadBalancerCommand$1.call(LoadBalancerCommand.java:180) ~[ribbon-loadbalancer-2.3.0.jar:2.3.0]
        at rx.Observable.unsafeSubscribe(Observable.java:10327) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.operators.OnSubscribeConcatMap.call(OnSubscribeConcatMap.java:94) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.operators.OnSubscribeConcatMap.call(OnSubscribeConcatMap.java:42) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.Observable.unsafeSubscribe(Observable.java:10327) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber$1.call(OperatorRetryWithPredicate.java:127) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.enqueue(TrampolineScheduler.java:73) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.schedule(TrampolineScheduler.java:52) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber.onNext(OperatorRetryWithPredicate.java:79) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber.onNext(OperatorRetryWithPredicate.java:45) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.util.ScalarSynchronousObservable$WeakSingleProducer.request(ScalarSynchronousObservable.java:276) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.Subscriber.setProducer(Subscriber.java:209) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.util.ScalarSynchronousObservable$JustOnSubscribe.call(ScalarSynchronousObservable.java:138) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.util.ScalarSynchronousObservable$JustOnSubscribe.call(ScalarSynchronousObservable.java:129) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.Observable.subscribe(Observable.java:10423) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.Observable.subscribe(Observable.java:10390) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.observables.BlockingObservable.blockForSingle(BlockingObservable.java:443) ~[rxjava-1.3.8.jar:1.3.8]
        at rx.observables.BlockingObservable.single(BlockingObservable.java:340) ~[rxjava-1.3.8.jar:1.3.8]
        at com.netflix.client.AbstractLoadBalancerAwareClient.executeWithLoadBalancer(AbstractLoadBalancerAwareClient.java:112) ~[ribbon-loadbalancer-2.3.0.jar:2.3.0]
        at org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient.execute(LoadBalancerFeignClient.java:83) ~[spring-cloud-openfeign-core-2.2.1.RELEASE.jar:2.2.1.RELEASE]
        at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:110) ~[feign-core-10.4.0.jar:na]
        at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:80) ~[feign-core-10.4.0.jar:na]
        at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103) ~[feign-core-10.4.0.jar:na]
        at com.sun.proxy.$Proxy98.hello(Unknown Source) ~[na:na]
        at com.example.nacosfeign.clients.DemoController.hello(DemoController.java:19) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_121]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_121]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_121]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_121]
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) ~[spring-webmvc-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) ~[tomcat-embed-core-9.0.39.jar:4.0.FR]
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.39.jar:4.0.FR]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:94) ~[spring-web-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.1.19.RELEASE.jar:5.1.19.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.39.jar:9.0.39]
        at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]

2.2 The debug process

We know that spring boot use feign(ribbon) to access remote services registered in a service registry.

But if some errors occur, how to debug this process?

2.3 The solution

We can create a config class to configure feign:

import feign.Logger;
import org.springframework.context.annotation.Bean;

public class FeignConfig {
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}

Notice the Logger is instance of the class feign.Logger. There are 4 levels :

  • NONE, No logging (DEFAULT).
  • BASIC, Log only the request method and URL and the response status code and execution time.
  • HEADERS, Log the basic information along with request and response headers.
  • FULL, Log the headers, body, and metadata for both requests and responses.

If you want to show the request URL(including host of the URL) , you can use BASIC:

import feign.Logger;
import org.springframework.context.annotation.Bean;

public class FeignConfig {
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.BASIC;
    }
}

Then we can configure FeignClient to use the config:

import com.example.nacosfeign.config.FeignConfig;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Map;

@FeignClient(name="nacos-provider-bswencw1", configuration = FeignConfig.class)
public interface DemoClient {
    @GetMapping("hello")
    Map<String, Object> hello();
}

At last, we should change our app logging level to DEBUG to show the logs:

Say our app’s package is prefixed by com.example:

server:
  port: 8086
spring:
  application:
    name: nacos-feign
  cloud:
    nacos:
      discovery:
        server-addr: 10.1.1.1:8848
logging:
  level:
    root: ERROR
    org.springframework.web: ERROR
    com.example: DEBUG

Then run the test again, we got this debug info:

2022-02-18 15:35:45.000  INFO 45588 --- [           main] c.e.nacosfeign.NacosFeignApplication     : No active profile set, falling back to default profiles: default
2022-02-18 15:35:47.732  INFO 45588 --- [           main] c.e.nacosfeign.NacosFeignApplication     : Started NacosFeignApplication in 4.065 seconds (JVM running for 8.322)
2022-02-18 15:36:16.404 DEBUG 45588 --- [nio-8086-exec-1] c.example.nacosfeign.clients.DemoClient  : [DemoClient#hello] ---> GET http://nacos-provider-/hello HTTP/1.1
2022-02-18 15:36:16.405 DEBUG 45588 --- [nio-8086-exec-1] c.example.nacosfeign.clients.DemoClient  : [DemoClient#hello] Content-Length: 2
2022-02-18 15:36:16.405 DEBUG 45588 --- [nio-8086-exec-1] c.example.nacosfeign.clients.DemoClient  : [DemoClient#hello] Content-Type: text/plain;charset=UTF-8
2022-02-18 15:36:16.405 DEBUG 45588 --- [nio-8086-exec-1] c.example.nacosfeign.clients.DemoClient  : [DemoClient#hello] 
2022-02-18 15:36:16.405 DEBUG 45588 --- [nio-8086-exec-1] c.example.nacosfeign.clients.DemoClient  : [DemoClient#hello] aa
2022-02-18 15:36:16.405 DEBUG 45588 --- [nio-8086-exec-1] c.example.nacosfeign.clients.DemoClient  : [DemoClient#hello] ---> END HTTP (2-byte body)
2022-02-18 15:36:19.253 DEBUG 45588 --- [nio-8086-exec-1] c.example.nacosfeign.clients.DemoClient  : [DemoClient#hello] <--- ERROR SocketTimeoutException: Read timed out (2847ms)
2022-02-18 15:36:19.254 DEBUG 45588 --- [nio-8086-exec-1] c.example.nacosfeign.clients.DemoClient  : [DemoClient#hello] java.net.SocketTimeoutException: Read timed out

It works!

3. Summary

In this post, I demonstrated how to debug the application that is using feign to access remote servcies, the key point is to change the logging level of feign using spring configuration class . That’s it, thanks for your reading.

 Home / cxf / CXF java.net.SocketTimeoutException: Read timed out

| December 08, 2013
| Updated : May 12, 2020
cxf,
sockettimeoutexception,

CXF java.net.SocketTimeoutException: Read timed out

This exception happens, when invoking the client and it takes 50-60 seconds after that  we get java.net.SocketTimeoutException: Read timed out, following are the stacktrace

Caused by: org.apache.cxf.interceptor.Fault: Could not send Message.
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage
(MessageSenderInterceptor.java:64)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:220)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:276)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:222)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:171)
… 26 more
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
at java.io.BufferedInputStream.read(BufferedInputStream.java:317)

This article explains about how to fix this exception in CXF way

Note

For running this client you need to refer the classes created on CXF Web Service Tutorial. This client is created for above service.

Required Libraries

You need to download following libraries in order to Generate CXF Client

  1. OpenJDK 8 / Corretto
  2. Eclipse 4.15
  3. CXF-3.3.6
  4. Tomcat 9

Following jar must be in classpath

  1. cxf-core-3.3.6.jar
  2. cxf-rt-bindings-soap-3.3.6.jar
  3. cxf-rt-databinding-jaxb-3.3.6.jar
  4. cxf-rt-features-logging-3.3.6.jar
  5. cxf-rt-frontend-jaxws-3.3.6.jar
  6. cxf-rt-frontend-simple-3.3.6.jar
  7. cxf-rt-transports-http-3.3.6.jar
  8. cxf-rt-wsdl-3.3.6.jar
  9. httpasyncclient-4.1.4.jar
  10. httpclient-4.5.12.jar
  11. httpcore-4.4.13.jar
  12. httpcore-nio-4.4.13.jar
  13. neethi-3.1.1.jar
  14. slf4j-api-1.7.29.jar
  15. slf4j-jdk14-1.7.29.jar
  16. spring-aop-5.1.14.RELEASE.jar
  17. spring-beans-5.1.14.RELEASE.jar
  18. spring-context-5.1.14.RELEASE.jar
  19. spring-core-5.1.14.RELEASE.jar
  20. spring-expression-5.1.14.RELEASE.jar
  21. spring-jcl-5.1.14.RELEASE.jar
  22. spring-web-5.1.14.RELEASE.jar
  23. stax2-api-3.1.4.jar
  24. woodstox-core-5.0.3.jar
  25. wsdl4j-1.6.3.jar
  26. xmlschema-core-2.2.5.jar

Fix java.net.SocketTimeoutException: Read timed out exception

You can use HTTPConduit and HTTPClientPolicy and need to set ConnectionTimeout and ReceiveTimeout when invoking the service, please see the below code

Note

Here we are using CXF’s JaxWsProxyFactoryBean, if you need to set timeout in JAX-WS way, you can set request timeout on request context property. See the code below
java.util.Map requestContext =((javax.xml.ws.BindingProvider) port).getRequestContext();
requestContext.put(com.sun.xml.internal.ws.request.timeout, new Long(600000));

Run Client

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;

import com.student.ChangeStudentDetails;
import com.student.Student;

// How to handle java.net.SocketTimeoutException: Read timed out exception

public final class StudentClient {public static void main(String args[]) throws Exception {JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
     
long timeout = 10000L;

      factory.setServiceClass

(ChangeStudentDetails.class);
      factory.setAddress
(«http://localhost:8080/CXFTutorial/ChangeStudent»);
     
factory.getInInterceptors().add(new LoggingInInterceptor());
      factory.getOutInterceptors
().add(new LoggingOutInterceptor());
      ChangeStudentDetails ChangeStudentService =
(ChangeStudentDetails) factory.create();

     
      Client client = ClientProxy.getClient

(ChangeStudentService);
     
if (client != null) {
         
HTTPConduit conduit = (HTTPConduit) client.getConduit();
          HTTPClientPolicy policy =
new HTTPClientPolicy();
          policy.setConnectionTimeout
(timeout);
          policy.setReceiveTimeout
(timeout);
          conduit.setClient
(policy);
     
}Student student = new Student();
      student.setName
(Rockey);
      Student changeName = ChangeStudentService.changeName
(student);
      System.out.println
(Server said:  + changeName.getName());
      System.exit
(0);
   
}
}

Output

Server said: Hello Rockey

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Java lang securityexception ошибка как исправить на андроид
  • Java lang runtimeexception ошибка андроид