@Slf4j public class ConfigClient {
private CloseableHttpClient httpClient; private RequestConfig requestConfig;
public ConfigClient() { this.httpClient = HttpClientBuilder.create().build(); // ① httpClient 客户端超时时间要大于长轮询约定的超时时间 this.requestConfig = RequestConfig.custom().setSocketTimeout(40000).build(); }
@SneakyThrows public void longPolling(String url, String dataId) { String endpoint = url + "?dataId=" + dataId; HttpGet request = new HttpGet(endpoint); CloseableHttpResponse response = httpClient.execute(request); switch (response.getStatusLine().getStatusCode()) { case 200: { BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity() .getContent())); StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); } response.close(); String configInfo = result.toString(); log.info("dataId: [{}] changed, receive configInfo: {}", dataId, configInfo); longPolling(url, dataId); break; } // ② 304 响应码标记配置未变更 case 304: { log.info("longPolling dataId: [{}] once finished, configInfo is unchanged, longPolling again", dataId); longPolling(url, dataId); break; } default: { throw new RuntimeException("unExcepted HTTP status code"); } }
}
public static void main(String[] args) { // httpClient 会打印很多 debug 日志,关闭掉 Logger logger = (Logger)LoggerFactory.getLogger("org.apache.http"); logger.setLevel(Level.INFO); logger.setAdditive(false);
ConfigClient configClient = new ConfigClient(); // ③ 对 dataId: user 进行配置监听 configClient.longPolling("http://127.0.0.1:8080/listener", "user"); }
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。