Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use CouchDB Change Notifications Continuous Changes from Java?

Tags:

couchdb

I am trying to use the couchdb (continuous) changes API from Java and find that after exhausting the list of current changes the stream seems to be closed, not stay open forever as it is supposed to.

The code I am using is below. I would expect to never drop out of the while loop, but do as soon as the currently existing changes are finished being streamed. I am relatively new to both couchdb and Java so may be missing something obvious. Can anyone show me how to write this correctly?

URL url = new URL("[path to database here]/_changes?feed=continuous";);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true); 
conn.setUseCaches(false); 
conn.setRequestProperty("Connection", "Keep-Alive"); 
conn.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while((line = reader.readLine()) != null){
    // do something with the line here
}
// Should never get here under normal circumstances
reader.close();
like image 793
Stephen Avatar asked Oct 28 '09 22:10

Stephen


2 Answers

There's actually a default timeout of 60000ms (60 seconds) unless a different timeout value or a heartbeat is provided. I updated the _changes wiki page back in October and included any defaults I came across in the code.

Setting the heartbeat basically means that you'll be watching for a timeout in the client, i.e. no newline for the heartbeat period means you've definitely lost your connection. I believe CouchDB disables its timeout check if there's a heartbeat.

In any case, you should probably expect the connection to be closed at some point and code for that condition.

like image 106
Matt Goodall Avatar answered Nov 23 '22 10:11

Matt Goodall


You can use &heartbeat=1000 to get couchdb sending new lines over the wire every second. That will keep your connection open until you disconnect and/or CouchDB gets shut down.

But you are right, I would also have expected that the connection won't close - seems as if also conn.setReadTimeout(0); doesn't help anything.

like image 32
Joscha Avatar answered Nov 23 '22 10:11

Joscha