dnet-hadoop/dhp-common/src/main/java/eu/dnetlib/dhp/message/MessageSender.java

58 lines
1.7 KiB
Java
Raw Normal View History

2021-02-03 16:42:36 +01:00
2021-02-04 09:45:46 +01:00
package eu.dnetlib.dhp.message;
2021-02-03 16:42:36 +01:00
2021-02-04 09:45:46 +01:00
import org.apache.http.client.config.RequestConfig;
2021-02-03 16:42:36 +01:00
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.SerializableEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MessageSender {
private static final Logger log = LoggerFactory.getLogger(MessageSender.class);
2021-02-04 09:45:46 +01:00
private static final int SOCKET_TIMEOUT_MS = 2000;
private static final int CONNECTION_REQUEST_TIMEOUT_MS = 2000;
private static final int CONNTECTION_TIMEOUT_MS = 2000;
2021-02-03 16:42:36 +01:00
private final String dnetMessageEndpoint;
public MessageSender(final String dnetMessageEndpoint) {
this.dnetMessageEndpoint = dnetMessageEndpoint;
}
public void sendMessage(final Message message) {
2021-02-04 09:45:46 +01:00
new Thread(() -> _sendMessage(message)).start();
}
private void _sendMessage(final Message message) {
2021-02-03 16:42:36 +01:00
final HttpPut req = new HttpPut(dnetMessageEndpoint);
req.setEntity(new SerializableEntity(message));
2021-02-04 09:45:46 +01:00
final RequestConfig requestConfig = RequestConfig
.custom()
.setConnectTimeout(CONNTECTION_TIMEOUT_MS)
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT_MS)
.setSocketTimeout(SOCKET_TIMEOUT_MS)
.build();
;
try (final CloseableHttpClient client = HttpClients
.custom()
.setDefaultRequestConfig(requestConfig)
.build();
2021-02-03 16:42:36 +01:00
final CloseableHttpResponse response = client.execute(req)) {
log.debug("Sent Message to " + dnetMessageEndpoint);
log.debug("MESSAGE:" + message);
} catch (final Throwable e) {
log.error("Error sending message to " + dnetMessageEndpoint + ", message content: " + message, e);
}
}
}