Java Code Examples for com.alipay.remoting.Connection#isFine()

The following examples show how to use com.alipay.remoting.Connection#isFine() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BoltClient.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
protected Connection getBoltConnection(RpcClient rpcClient, URL url) throws RemotingException {
    Url boltUrl = createBoltUrl(url);
    try {
        Connection connection = rpcClient.getConnection(boltUrl, connectTimeout);
        if (connection == null || !connection.isFine()) {
            if (connection != null) {
                connection.close();
            }
            throw new RemotingException("Get bolt connection failed for boltUrl: " + boltUrl);
        }
        return connection;
    } catch (InterruptedException e) {
        throw new RuntimeException(
            "BoltClient rpcClient.getConnection InterruptedException! target boltUrl:"
                    + boltUrl, e);
    }
}
 
Example 2
Source File: SessionServerConnectionFactory.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
/**
 * register connection
 *
 * @param processId
 * @param connectIds
 * @param connection
 */
public void registerSession(String processId, Set<String> connectIds, Connection connection) {
    if (!connection.isFine()) {
        return;
    }
    String sessionConnAddress = NetUtil.toAddressString(connection.getRemoteAddress());
    LOGGER.info("session({}, processId={}) registered", sessionConnAddress, processId);

    SESSION_CONN_PROCESS_ID_MAP.put(sessionConnAddress, processId);

    Set<String> connectIdSet = PROCESS_ID_CONNECT_ID_MAP
            .computeIfAbsent(processId, k -> ConcurrentHashMap.newKeySet());
    connectIdSet.addAll(connectIds);

    Pair pair = PROCESS_ID_SESSION_CONN_MAP.computeIfAbsent(processId, k -> new Pair(new ConcurrentHashMap<>()));
    pair.getConnections().put(sessionConnAddress, connection);

}
 
Example 3
Source File: SessionServerNotifier.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
private void doNotify(NotifyCallback notifyCallback) {
    Connection connection = notifyCallback.connection;
    DataChangeRequest request = notifyCallback.request;
    try {
        //check connection active
        if (!connection.isFine()) {
            LOGGER
                .info(String
                    .format(
                        "connection from sessionServer(%s) is not fine, so ignore notify, retryTimes=%s,request=%s",
                        connection.getRemoteAddress(), notifyCallback.retryTimes, request));
            return;
        }
        Server sessionServer = boltExchange.getServer(dataServerConfig.getPort());
        sessionServer.sendCallback(sessionServer.getChannel(connection.getRemoteAddress()),
            request, notifyCallback, dataServerConfig.getRpcTimeout());
    } catch (Exception e) {
        LOGGER.error(String.format(
            "invokeWithCallback failed: sessionServer(%s),retryTimes=%s, request=%s",
            connection.getRemoteAddress(), notifyCallback.retryTimes, request), e);
        onFailed(notifyCallback);
    }
}
 
Example 4
Source File: ClientConnection.java    From sofa-registry with Apache License 2.0 5 votes vote down vote up
/**
 * Connect boolean.
 *
 * @return the boolean
 */
private boolean connect() {
    Random random = new Random();
    Connection connection = null;
    List<ServerNode> serverNodes = new ArrayList<ServerNode>(serverManager.getServerList());
    // shuffle server list to make server connections as discrete as possible
    Collections.shuffle(serverNodes);
    for (ServerNode serverNode : serverNodes) {
        try {
            connection = connect(serverNode);
            if (null != connection && connection.isFine()) {
                resetRegister();
                LOGGER.info("[Connect] Successfully connected to server: {}", serverNode);
                break;
            } else {
                recycle(connection);
            }

            Thread.sleep(random.nextInt(RECONNECTING_DELAY));
        } catch (Exception e) {
            LOGGER.error("[Connect] Failed trying connect to {}", serverNode, e);
        }
    }

    if (null != connection && connection.isFine()) {
        clientConnection = connection;
        return true;
    }
    return false;
}
 
Example 5
Source File: BoltServer.java    From sofa-registry with Apache License 2.0 5 votes vote down vote up
@Override
public void close(Channel channel) {
    if (null != channel) {
        channels.remove(NetUtil.toAddressString(channel.getRemoteAddress()));
        BoltChannel boltChannel = (BoltChannel) channel;
        Connection connection = boltChannel.getConnection();
        if (null != connection && connection.isFine()) {
            connection.close();
        }
    }
}
 
Example 6
Source File: DataServerNodeFactory.java    From sofa-registry with Apache License 2.0 5 votes vote down vote up
/**
 * remove dataserver by specific datacenter and ip
 *
 * @param dataCenter
 * @param ip
 */
public static void remove(String dataCenter, String ip, DataServerConfig dataServerConfig) {
    if (MAP.containsKey(dataCenter)) {
        Map<String, DataServerNode> map = MAP.get(dataCenter);
        if (map != null) {
            DataServerNode dataServerNode = map.get(ip);
            Connection connection = dataServerNode.getConnection();
            if (connection != null && connection.isFine()) {
                connection.close();
            }
            map.remove(ip);
        }
    }
    refreshConsistent(dataCenter, dataServerConfig);
}
 
Example 7
Source File: NotifyFetchDatumHandler.java    From sofa-registry with Apache License 2.0 5 votes vote down vote up
/**
 * 拉取数据
 *
 * @param targetIp
 * @param dataCenter
 * @param dataInfoId
 */
private void fetchDatum(String targetIp, String dataCenter, String dataInfoId) {
    while (dataServerConnectionFactory.getConnection(targetIp) != null) {
        Connection connection = dataServerConnectionFactory.getConnection(targetIp);
        if (connection == null || !connection.isFine()) {
            throw new RuntimeException(String.format("connection of %s is not available",
                targetIp));
        }
        try {
            Server syncServer = boltExchange.getServer(dataServerConfig.getSyncDataPort());
            GenericResponse<Map<String, Datum>> response = (GenericResponse<Map<String, Datum>>) syncServer
                .sendSync(syncServer.getChannel(connection.getRemoteAddress()),
                    new GetDataRequest(dataInfoId, dataCenter),
                    dataServerConfig.getRpcTimeout());
            if (response.isSuccess()) {
                Datum datum = response.getData().get(dataCenter);

                if (datum != null) {
                    // wrap by WordCache
                    datum = Datum.internDatum(datum);

                    dataChangeEventCenter.sync(DataChangeTypeEnum.COVER,
                        DataSourceTypeEnum.BACKUP, datum);
                    LOGGER
                        .info(
                            "[NotifyFetchDatumHandler] fetch datum success,dataInfoId={},dataCenter={},targetIp={}",
                            datum.getDataInfoId(), datum.getDataCenter(), targetIp);
                }
                break;
            } else {
                throw new RuntimeException(response.getMessage());
            }
        } catch (Exception e) {
            LOGGER.error("[NotifyFetchDatumHandler] fetch datum error", e);
            TimeUtil.randomDelay(500);
        }
    }
}
 
Example 8
Source File: MetaServerConnectionFactory.java    From sofa-registry with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param dataCenter
 */
public void remove(String dataCenter) {
    Map<String, Connection> map = getConnections(dataCenter);
    if (!map.isEmpty()) {
        for (Connection connection : map.values()) {
            if (connection.isFine()) {
                connection.close();
            }
        }
    }
    MAP.remove(dataCenter);
}
 
Example 9
Source File: LocalDataServerChangeEventHandler.java    From sofa-registry with Apache License 2.0 5 votes vote down vote up
/**
 * connect specific dataserver
 *
 * @param dataCenter
 * @param ip
 */
private void connectDataServer(String dataCenter, String ip) {
    Connection conn = null;
    for (int tryCount = 0; tryCount < TRY_COUNT; tryCount++) {
        try {
            conn = ((BoltChannel) dataNodeExchanger.connect(new URL(ip, dataServerConfig
                .getSyncDataPort()))).getConnection();
            break;
        } catch (Exception e) {
            LOGGER.error(
                "[LocalDataServerChangeEventHandler] connect dataServer {} in {} error",
                ip, dataCenter, e);
            TimeUtil.randomDelay(3000);
        }
    }
    if (conn == null || !conn.isFine()) {
        LOGGER
            .error(
                "[LocalDataServerChangeEventHandler] connect dataserver {} in {} failed five times",
                ip, dataCenter);
        throw new RuntimeException(
            String
                .format(
                    "[LocalDataServerChangeEventHandler] connect dataserver %s in %s failed five times,dataServer will not work,please check connect!",
                    ip, dataCenter));
    }
    LOGGER
        .info(
            "[LocalDataServerChangeEventHandler] connect dataserver in {} success,remote={},local={}",
            dataCenter, conn.getRemoteAddress(), conn.getLocalAddress());
    //maybe get dataNode from metaServer,current has not start! register dataNode info to factory,wait for connect task next execute
    DataServerNodeFactory.register(new DataServerNode(ip, dataCenter, conn),
        dataServerConfig);
}
 
Example 10
Source File: DataServerChangeEventHandler.java    From sofa-registry with Apache License 2.0 5 votes vote down vote up
/**
 * connect specific dataserver
 *
 * @param dataCenter
 * @param ip
 */
private void connectDataServer(String dataCenter, String ip) {
    Connection conn = null;
    for (int tryCount = 0; tryCount < TRY_COUNT; tryCount++) {
        try {
            conn = ((BoltChannel) dataNodeExchanger.connect(new URL(ip, dataServerConfig
                .getSyncDataPort()))).getConnection();
            break;
        } catch (Exception e) {
            LOGGER.error("[DataServerChangeEventHandler] connect dataServer {} in {} error",
                ip, dataCenter, e);
            TimeUtil.randomDelay(3000);
        }
    }
    if (conn == null || !conn.isFine()) {
        LOGGER.error(
            "[DataServerChangeEventHandler] connect dataServer {} in {} failed five times", ip,
            dataCenter);
        throw new RuntimeException(
            String
                .format(
                    "[DataServerChangeEventHandler] connect dataServer %s in %s failed five times,dataServer will not work,please check connect!",
                    ip, dataCenter));
    }
    //maybe get dataNode from metaServer,current has not start! register dataNode info to factory,wait for connect task next execute
    DataServerNodeFactory.register(new DataServerNode(ip, dataCenter, conn), dataServerConfig);
}
 
Example 11
Source File: RpcServer.java    From sofa-bolt with Apache License 2.0 5 votes vote down vote up
/**
 * check whether a {@link Url} connected
 *
 * @param url
 * @return
 */
public boolean isConnected(Url url) {
    Connection conn = this.rpcRemoting.connectionManager.get(url.getUniqueKey());
    if (null != conn) {
        return conn.isFine();
    }
    return false;
}
 
Example 12
Source File: BoltClientTransport.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
protected void checkConnection() throws SofaRpcException {

        Connection connection = fetchConnection();
        if (connection == null) {
            throw new SofaRpcException(RpcErrorType.CLIENT_NETWORK, "connection is null");
        }
        if (!connection.isFine()) {
            throw new SofaRpcException(RpcErrorType.CLIENT_NETWORK, "connection is not fine");
        }
    }
 
Example 13
Source File: DefaultMetaServiceImpl.java    From sofa-registry with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, Set<String>> getMetaServerMap() {
    HashMap<String, Set<String>> map = new HashMap<>();
    Set<String> set = dataServerConfig.getMetaServerIpAddresses();

    Map<String, Connection> connectionMap = metaServerConnectionFactory
        .getConnections(dataServerConfig.getLocalDataCenter());
    Connection connection = null;
    try {
        if (connectionMap.isEmpty()) {
            List<String> list = new ArrayList(set);
            Collections.shuffle(list);
            connection = ((BoltChannel) metaNodeExchanger.connect(new URL(list.iterator()
                .next(), dataServerConfig.getMetaServerPort()))).getConnection();
        } else {
            List<Connection> connections = new ArrayList<>(connectionMap.values());
            Collections.shuffle(connections);
            connection = connections.iterator().next();
            if (!connection.isFine()) {
                connection = ((BoltChannel) metaNodeExchanger.connect(new URL(connection
                    .getRemoteIP(), dataServerConfig.getMetaServerPort()))).getConnection();
            }
        }

        GetNodesRequest request = new GetNodesRequest(NodeType.META);
        final Connection finalConnection = connection;
        Object obj = metaNodeExchanger.request(new Request() {
            @Override
            public Object getRequestBody() {
                return request;
            }

            @Override
            public URL getRequestUrl() {
                return new URL(finalConnection.getRemoteIP(), finalConnection.getRemotePort());
            }
        }).getResult();
        if (obj instanceof NodeChangeResult) {
            NodeChangeResult<MetaNode> result = (NodeChangeResult<MetaNode>) obj;

            Map<String, Map<String, MetaNode>> metaNodesMap = result.getNodes();
            if (metaNodesMap != null && !metaNodesMap.isEmpty()) {
                Map<String, MetaNode> metaNodeMap = metaNodesMap.get(dataServerConfig
                    .getLocalDataCenter());
                if (metaNodeMap != null && !metaNodeMap.isEmpty()) {
                    map.put(dataServerConfig.getLocalDataCenter(), metaNodeMap.keySet());
                } else {
                    LOGGER
                        .error(
                            "[DefaultMetaServiceImpl] refresh connections from metaServer {} has no result!",
                            connection.getRemoteIP());
                }
            }
        }
    } catch (Exception e) {
        String con = connection != null ? connection.getRemoteIP() : "null";
        LOGGER.error("[DefaultMetaServiceImpl] refresh connections from metaServer error : {}",
            con, e);
        LOGGER
            .warn(
                "[DefaultMetaServiceImpl] refresh connections from metaServer error,refresh leader : {}",
                con);
        throw new RuntimeException(
            "[DefaultMetaServiceImpl] refresh connections from metaServer error!", e);
    }
    return map;
}
 
Example 14
Source File: DefaultMetaServiceImpl.java    From sofa-registry with Apache License 2.0 4 votes vote down vote up
@Override
public ProvideData fetchData(String dataInfoId) {

    Map<String, Connection> connectionMap = metaServerConnectionFactory
        .getConnections(dataServerConfig.getLocalDataCenter());
    String leader = getLeader().getIp();
    if (connectionMap.containsKey(leader)) {
        Connection connection = connectionMap.get(leader);
        if (connection.isFine()) {
            try {
                Request<FetchProvideDataRequest> request = new Request<FetchProvideDataRequest>() {

                    @Override
                    public FetchProvideDataRequest getRequestBody() {

                        return new FetchProvideDataRequest(dataInfoId);
                    }

                    @Override
                    public URL getRequestUrl() {
                        return new URL(connection.getRemoteIP(), connection.getRemotePort());
                    }
                };

                Response response = metaNodeExchanger.request(request);

                Object result = response.getResult();
                if (result instanceof ProvideData) {
                    return (ProvideData) result;
                } else {
                    LOGGER.error("fetch null provider data!");
                    throw new RuntimeException("MetaNodeService fetch null provider data!");
                }
            } catch (Exception e) {
                LOGGER.error("fetch provider data error! " + e.getMessage(), e);
                throw new RuntimeException("fetch provider data error! " + e.getMessage(), e);
            }
        }
    }
    String newip = refreshLeader().getIp();
    LOGGER.warn(
        "[ConnectionRefreshTask] refresh connections metaServer not fine,refresh leader : {}",
        newip);
    return null;

}
 
Example 15
Source File: LocalDataServerChangeEventHandler.java    From sofa-registry with Apache License 2.0 4 votes vote down vote up
/**
 * notify other dataservers that this server is online newly
 *
 * @param changeVersion
 */
private void notifyOnline(long changeVersion) {
    Map<String, DataServerNode> dataServerNodeMap = DataServerNodeFactory
        .getDataServerNodes(dataServerConfig.getLocalDataCenter());
    for (Entry<String, DataServerNode> serverEntry : dataServerNodeMap.entrySet()) {
        while (true) {
            String ip = serverEntry.getKey();
            DataServerNode dataServerNode = DataServerNodeFactory.getDataServerNode(
                dataServerConfig.getLocalDataCenter(), ip);

            if (dataServerNode == null) {
                LOGGER
                    .warn(
                        "notify Online dataserver {} has not existed in DataServerNodeFactory!version={}",
                        ip, changeVersion);
                break;
            }
            try {
                final Connection connection = dataServerNode.getConnection();
                if (connection == null || !connection.isFine()) {
                    if (connection == null) {
                        LOGGER
                            .warn(
                                "notify Online dataserver connect not existed,ip={},version={}",
                                ip, changeVersion);
                    } else {
                        LOGGER
                            .warn(
                                "notify Online dataserver connect not fine!remote={},local={},version={}",
                                connection.getRemoteAddress(),
                                connection.getLocalAddress(), changeVersion);
                    }
                    //connect now and registry connect
                    connectDataServer(dataServerConfig.getLocalDataCenter(), ip);
                    //maybe get dataNode from metaServer,current has not connected!wait for connect task execute
                    TimeUtil.randomDelay(1000);
                    continue;
                }
                CommonResponse response = (CommonResponse) dataNodeExchanger.request(
                    new Request() {

                        @Override
                        public Object getRequestBody() {
                            return new NotifyOnlineRequest(DataServerConfig.IP,
                                changeVersion);
                        }

                        @Override
                        public URL getRequestUrl() {
                            return new URL(connection.getRemoteIP(), connection
                                .getRemotePort());
                        }
                    }).getResult();
                if (response.isSuccess()) {
                    LOGGER.info("notify {} that i am newer success,version={}", ip,
                        changeVersion);
                    break;
                } else {
                    throw new RuntimeException(response.getMessage());
                }
            } catch (Exception e) {
                LOGGER.info("notify {} that i am newer failed", ip);
                LOGGER.error("notify {} that i am newer error", ip, e);
                TimeUtil.randomDelay(500);
            }
        }
    }
}
 
Example 16
Source File: ReuseBoltClientConnectionManager.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isConnectionFine(RpcClient rpcClient, ClientTransportConfig transportConfig, Url url) {
    Connection connection = this.getConnection(rpcClient, transportConfig, url);
    return connection != null && connection.isFine();
}