开发者社区> 问答> 正文

配置中心长轮询实现中怎样实现客户端?

配置中心长轮询实现中怎样实现客户端?

展开
收起
Aries- 2022-05-10 17:22:31 268 0
来自:阿里技术
1 条回答
写回答
取消 提交回答
  • @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"); }

    }

    2022-05-10 20:01:37
    赞同 展开评论 打赏
问答地址:
来源圈子
更多
收录在圈子:
+ 订阅
问答排行榜
最热
最新

相关电子书

更多
探索连接的最后十秒”落时”的网关 立即下载
一招玩转微服务注册&配置中心 立即下载
微信客户端怎样应对弱网络 立即下载