参考自rocketmq

    1. if (this.lockChannelTables.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) {
    2. try {
    3. boolean createNewConnection;
    4. cw = this.channelTables.get(addr);
    5. if (cw != null) {
    6. if (cw.isOK()) {
    7. return cw.getChannel();
    8. } else if (!cw.getChannelFuture().isDone()) {
    9. createNewConnection = false;
    10. } else {
    11. this.channelTables.remove(addr);
    12. createNewConnection = true;
    13. }
    14. } else {
    15. createNewConnection = true;
    16. }
    17. if (createNewConnection) {
    18. ChannelFuture channelFuture = this.bootstrap.connect(RemotingHelper.string2SocketAddress(addr));
    19. log.info("createChannel: begin to connect remote host[{}] asynchronously", addr);
    20. cw = new ChannelWrapper(channelFuture);
    21. this.channelTables.put(addr, cw);
    22. }
    23. } catch (Exception e) {
    24. log.error("createChannel: create channel exception", e);
    25. } finally {
    26. this.lockChannelTables.unlock();
    27. }
    28. } else {
    29. log.warn("createChannel: try to lock channel table, but timeout, {}ms", LOCK_TIMEOUT_MILLIS);
    30. }