com.alipay.remoting.Connection Java Examples

The following examples show how to use com.alipay.remoting.Connection. 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: BasicUsage_AsyncProcessor_Test.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerSyncUsingAddress() throws Exception {
    Connection clientConn = client.createStandaloneConnection(ip, port, 1000);
    String remote = RemotingUtil.parseRemoteAddress(clientConn.getChannel());
    String local = RemotingUtil.parseLocalAddress(clientConn.getChannel());
    logger.warn("Client say local:" + local);
    logger.warn("Client say remote:" + remote);

    for (int i = 0; i < invokeTimes; i++) {
        RequestBody req1 = new RequestBody(1, RequestBody.DEFAULT_CLIENT_STR);
        String serverres = (String) client.invokeSync(clientConn, req1, 1000);
        Assert.assertEquals(serverres, RequestBody.DEFAULT_SERVER_RETURN_STR);

        Assert.assertNotNull(serverConnectProcessor.getConnection());
        // only when client invoked, the remote address can be get by UserProcessor
        // otherwise, please use ConnectionEventProcessor
        String remoteAddr = serverUserProcessor.getRemoteAddr();
        RequestBody req = new RequestBody(1, RequestBody.DEFAULT_SERVER_STR);
        String clientres = (String) server.getRpcServer().invokeSync(remoteAddr, req, 1000);
        Assert.assertEquals(clientres, RequestBody.DEFAULT_CLIENT_RETURN_STR);
    }

    Assert.assertTrue(serverConnectProcessor.isConnected());
    Assert.assertEquals(1, serverConnectProcessor.getConnectTimes());
    Assert.assertEquals(invokeTimes, serverUserProcessor.getInvokeTimes());
}
 
Example #2
Source File: AloneBoltClientConnectionManager.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 通过配置获取长连接
 *
 * @param rpcClient       bolt客户端
 * @param transportConfig 传输层配置
 * @param url             传输层地址
 * @return 长连接
 */
public Connection getConnection(RpcClient rpcClient, ClientTransportConfig transportConfig, Url url) {
    if (rpcClient == null || transportConfig == null || url == null) {
        return null;
    }
    Connection connection;
    try {
        connection = rpcClient.getConnection(url, url.getConnectTimeout());
    } catch (InterruptedException | RemotingException e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_GET_CONNECTION),e);
    }
    if (connection == null) {
        return null;
    }

    return connection;
}
 
Example #3
Source File: DataDigestResource.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
public Map<String, List<String>> getMetaServerList() {

        Map<String, List<String>> map = new HashMap<>();
        Set<String> allDataCenter = new HashSet<>(metaServerConnectionFactory.getAllDataCenters());
        for (String dataCenter : allDataCenter) {

            List<String> list = map.computeIfAbsent(dataCenter, k -> new ArrayList<>());

            Map<String, Connection> metaConnections = metaServerConnectionFactory.getConnections(dataCenter);
            if (metaConnections != null && !metaConnections.isEmpty()) {

                metaConnections.forEach((ip, connection) -> {
                    if (connection != null && connection.isFine()) {
                        list.add(connection.getRemoteIP());
                    }
                });
            }
        }
        return map;
    }
 
Example #4
Source File: BasicUsage_SHARE_SAME_SERVER_Test.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void test_e_ServerSync() throws Exception {
    Connection clientConn = client.createStandaloneConnection(ip, port, 1000);

    for (int i = 0; i < invokeTimes; i++) {
        RequestBody req1 = new RequestBody(1, RequestBody.DEFAULT_CLIENT_STR);
        String serverres = (String) client.invokeSync(clientConn, req1, 1000);
        Assert.assertEquals(serverres, RequestBody.DEFAULT_SERVER_RETURN_STR);

        Assert.assertNotNull(serverConnectProcessor.getConnection());
        Connection serverConn = serverConnectProcessor.getConnection();
        RequestBody req = new RequestBody(1, RequestBody.DEFAULT_SERVER_STR);
        String clientres = (String) server.getRpcServer().invokeSync(serverConn, req, 1000);
        Assert.assertEquals(clientres, RequestBody.DEFAULT_CLIENT_RETURN_STR);
    }

    Assert.assertTrue(serverConnectProcessor.isConnected());
    Assert.assertEquals(5, serverConnectProcessor.getConnectTimes());
    Assert.assertEquals(invokeTimes * 5, serverUserProcessor.getInvokeTimes());
}
 
Example #5
Source File: BasicUsage_ProcessInIoThread_Test.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerSyncUsingConnection() throws Exception {
    Connection clientConn = client.createStandaloneConnection(ip, port, 1000);

    for (int i = 0; i < invokeTimes; i++) {
        RequestBody req1 = new RequestBody(1, RequestBody.DEFAULT_CLIENT_STR);
        String serverres = (String) client.invokeSync(clientConn, req1, 1000);
        Assert.assertEquals(serverres, RequestBody.DEFAULT_SERVER_RETURN_STR);

        Assert.assertNotNull(serverConnectProcessor.getConnection());
        Connection serverConn = serverConnectProcessor.getConnection();
        RequestBody req = new RequestBody(1, RequestBody.DEFAULT_SERVER_STR);
        String clientres = (String) server.getRpcServer().invokeSync(serverConn, req, 1000);
        Assert.assertEquals(clientres, RequestBody.DEFAULT_CLIENT_RETURN_STR);
    }

    Assert.assertTrue(serverConnectProcessor.isConnected());
    Assert.assertEquals(1, serverConnectProcessor.getConnectTimes());
    Assert.assertEquals(invokeTimes, serverUserProcessor.getInvokeTimes());
}
 
Example #6
Source File: ScheduledDisconnectStrategyTest.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseFreshSelectConnections_byUserSetting() throws RemotingException,
                                                           InterruptedException {
    System.setProperty(Configs.RETRY_DETECT_PERIOD, "500");
    System.setProperty(Configs.CONN_MONITOR_INITIAL_DELAY, "2000");
    System.setProperty(Configs.CONN_MONITOR_PERIOD, "100");
    System.setProperty(Configs.CONN_THRESHOLD, "0");
    doInit(false, true);

    String addr = "127.0.0.1:" + port + "?zone=RZONE&_CONNECTIONNUM=1";
    Url url = addressParser.parse(addr);

    final Connection connection = client.getConnection(url, 1000);
    connection.addInvokeFuture(new DefaultInvokeFuture(1, null, null, RpcCommandType.REQUEST,
        null));
    Thread.sleep(2100);
    Assert.assertTrue(0 == clientDisConnectProcessor.getDisConnectTimes());
    Assert.assertEquals(1, clientConnectProcessor.getConnectTimes());
    connection.removeInvokeFuture(1);
    /* Monitor task sleep 500ms*/
    Thread.sleep(100);
    Assert.assertEquals(1, clientDisConnectProcessor.getDisConnectTimes());
    Thread.sleep(500);
    Assert.assertTrue(0 <= clientDisConnectProcessor.getDisConnectTimes());
}
 
Example #7
Source File: BoltClient.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
@Override
public Channel connect(URL url) {
    if (url == null) {
        throw new IllegalArgumentException("Create connection url can not be null!");
    }
    try {
        Connection connection = getBoltConnection(rpcClient, url);
        BoltChannel channel = new BoltChannel();
        channel.setConnection(connection);
        return channel;

    } catch (RemotingException e) {
        LOGGER
            .error("Bolt client connect server got a RemotingException! target url:" + url, e);
        throw new RuntimeException("Bolt client connect server got a RemotingException!", e);
    }
}
 
Example #8
Source File: RpcConnectionManagerTest.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddAndRemoveConnection() {
    String poolKey = ip + ":" + port;
    int connectTimeoutMillis = 1000;

    Connection conn = null;
    try {
        conn = cm.create(ip, port, connectTimeoutMillis);
        conn.addPoolKey(poolKey);
    } catch (Exception e) {
        logger.error("", e);
    }
    cm.add(conn);
    Assert.assertEquals(1, cm.count(poolKey));
    cm.remove(conn);
    Assert.assertEquals(0, cm.count(poolKey));
}
 
Example #9
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 #10
Source File: SessionServerConnectionFactory.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
/**
 * get connections of SessionServer ( Randomly select a connection for each session )
 */
public List<Connection> getSessionConnections() {
    List<Connection> list = new ArrayList<>(PROCESS_ID_SESSION_CONN_MAP.size());
    Collection<Pair> pairs = PROCESS_ID_SESSION_CONN_MAP.values();
    if (pairs != null) {
        for (Pair pair : pairs) {
            Object[] conns = pair.getConnections().values().toArray();
            if (conns.length > 0) {
                int n = pair.roundRobin.incrementAndGet();
                if (n < 0) {
                    pair.roundRobin.compareAndSet(n, 0);
                    n = (n == Integer.MIN_VALUE) ? 0 : Math.abs(n);
                }
                n = n % conns.length;
                list.add((Connection) conns[n]);
            }
        }
    }
    return list;
}
 
Example #11
Source File: ScheduledDisconnectStrategyTest.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloseFreshSelectConnections_bySystemSetting() throws RemotingException,
                                                             InterruptedException {
    System.setProperty(Configs.RETRY_DETECT_PERIOD, "500");
    System.setProperty(Configs.CONN_MONITOR_INITIAL_DELAY, "2000");
    System.setProperty(Configs.CONN_MONITOR_PERIOD, "100");
    System.setProperty(Configs.CONN_THRESHOLD, "0");
    doInit(true, false);

    String addr = "127.0.0.1:" + port + "?zone=RZONE&_CONNECTIONNUM=1";
    Url url = addressParser.parse(addr);

    final Connection connection = client.getConnection(url, 1000);
    connection.addInvokeFuture(new DefaultInvokeFuture(1, null, null, RpcCommandType.REQUEST,
        null));
    Thread.sleep(2100);
    Assert.assertTrue(0 == clientDisConnectProcessor.getDisConnectTimes());
    Assert.assertEquals(1, clientConnectProcessor.getConnectTimes());
    connection.removeInvokeFuture(1);
    /* Monitor task sleep 500ms*/
    Thread.sleep(100);
    Assert.assertTrue(0 <= clientDisConnectProcessor.getDisConnectTimes());
    Thread.sleep(500);
    Assert.assertTrue(0 <= clientDisConnectProcessor.getDisConnectTimes());
}
 
Example #12
Source File: BasicUsageTest.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerSyncUsingConnection1() throws Exception {
    for (int i = 0; i < invokeTimes; i++) {
        RequestBody req1 = new RequestBody(1, RequestBody.DEFAULT_CLIENT_STR);
        String serverres = (String) client.invokeSync(addr, req1, 1000);
        Assert.assertEquals(serverres, RequestBody.DEFAULT_SERVER_RETURN_STR);

        Assert.assertNotNull(serverConnectProcessor.getConnection());
        Connection serverConn = serverConnectProcessor.getConnection();
        RequestBody req = new RequestBody(1, RequestBody.DEFAULT_SERVER_STR);
        String clientres = (String) server.getRpcServer().invokeSync(serverConn, req, 1000);
        Assert.assertEquals(clientres, RequestBody.DEFAULT_CLIENT_RETURN_STR);
    }

    Assert.assertTrue(serverConnectProcessor.isConnected());
    Assert.assertEquals(1, serverConnectProcessor.getConnectTimes());
    Assert.assertEquals(invokeTimes, serverUserProcessor.getInvokeTimes());
}
 
Example #13
Source File: RpcConnectionManagerTest.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddWconnithPoolKey_multiPoolKey() throws InterruptedException {
    Connection conn = getAConn();
    cm.add(conn, poolKey);
    cm.add(conn, "GROUP1");
    cm.add(conn, "GROUP2");
    Assert.assertEquals(1, cm.count(poolKey));
    Assert.assertEquals(1, cm.count("GROUP1"));
    Assert.assertEquals(1, cm.count("GROUP2"));

    cm.remove(conn, poolKey);
    Assert.assertTrue(conn.isFine());
    Assert.assertTrue(cm.get(poolKey) == null);
    Assert.assertTrue(cm.get("GROUP1").isFine());
    Assert.assertTrue(cm.get("GROUP2").isFine());

    cm.remove(conn, "GROUP1");
    cm.remove(conn, "GROUP2");
    Thread.sleep(1000);
    Assert.assertFalse(conn.isFine());
    Assert.assertTrue(cm.get(poolKey) == null);
    Assert.assertTrue(cm.get("GROUP1") == null);
    Assert.assertTrue(cm.get("GROUP2") == null);
}
 
Example #14
Source File: BasicUsage_ProtocolV1_Test.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerSyncUsingAddress() throws Exception {
    Connection clientConn = client.createStandaloneConnection(ip, port, 1000);
    String remote = RemotingUtil.parseRemoteAddress(clientConn.getChannel());
    String local = RemotingUtil.parseLocalAddress(clientConn.getChannel());
    logger.warn("Client say local:" + local);
    logger.warn("Client say remote:" + remote);

    for (int i = 0; i < invokeTimes; i++) {
        RequestBody req1 = new RequestBody(1, RequestBody.DEFAULT_CLIENT_STR);
        String serverres = (String) client.invokeSync(clientConn, req1, 1000);
        Assert.assertEquals(serverres, RequestBody.DEFAULT_SERVER_RETURN_STR);

        Assert.assertNotNull(serverConnectProcessor.getConnection());
        // only when client invoked, the remote address can be get by UserProcessor
        // otherwise, please use ConnectionEventProcessor
        String remoteAddr = serverUserProcessor.getRemoteAddr();
        RequestBody req = new RequestBody(1, RequestBody.DEFAULT_SERVER_STR);
        String clientres = (String) server.getRpcServer().invokeSync(remoteAddr, req, 1000);
        Assert.assertEquals(clientres, RequestBody.DEFAULT_CLIENT_RETURN_STR);
    }

    Assert.assertTrue(serverConnectProcessor.isConnected());
    Assert.assertEquals(1, serverConnectProcessor.getConnectTimes());
    Assert.assertEquals(invokeTimes, serverUserProcessor.getInvokeTimes());
}
 
Example #15
Source File: RpcConnectionManagerTest.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnectionCloseAndConnectionManagerRemove() throws RemotingException,
                                                           InterruptedException {
    final Url addr = new Url(ip, port);

    this.addressParser.initUrlArgs(addr);
    Connection conn = null;
    try {
        conn = cm.getAndCreateIfAbsent(addr);
    } catch (InterruptedException e) {
        Assert.fail("InterruptedException!");
    }

    Assert.assertEquals(1, cm.count(addr.getUniqueKey()));
    conn.close();
    Thread.sleep(100);
    Assert.assertEquals(0, cm.count(addr.getUniqueKey()));
}
 
Example #16
Source File: RemotingUtilTest.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
/**
 * parse channel to get address(format [ip:port])
 */
@Test
public void testParseRemoteAddress() {
    Connection conn;
    try {
        parser.initUrlArgs(connAddress);
        conn = client.getConnection(connAddress, 1000);
        Channel channel = conn.getChannel();
        String res = RemotingUtil.parseRemoteAddress(channel);
        Assert.assertEquals(connAddress.getUniqueKey(), res);
    } catch (Exception e) {
        e.printStackTrace();
        Assert.assertFalse(true);
    }

}
 
Example #17
Source File: BasicUsageTest.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerSyncUsingAddress() throws Exception {
    Connection clientConn = client.createStandaloneConnection(ip, port, 1000);
    String remote = RemotingUtil.parseRemoteAddress(clientConn.getChannel());
    String local = RemotingUtil.parseLocalAddress(clientConn.getChannel());
    logger.warn("Client say local:" + local);
    logger.warn("Client say remote:" + remote);

    for (int i = 0; i < invokeTimes; i++) {
        RequestBody req1 = new RequestBody(1, RequestBody.DEFAULT_CLIENT_STR);
        String serverres = (String) client.invokeSync(clientConn, req1, 1000);
        Assert.assertEquals(serverres, RequestBody.DEFAULT_SERVER_RETURN_STR);

        Assert.assertNotNull(serverConnectProcessor.getConnection());
        // only when client invoked, the remote address can be get by UserProcessor
        // otherwise, please use ConnectionEventProcessor
        String remoteAddr = serverUserProcessor.getRemoteAddr();
        RequestBody req = new RequestBody(1, RequestBody.DEFAULT_SERVER_STR);
        String clientres = (String) server.getRpcServer().invokeSync(remoteAddr, req, 1000);
        Assert.assertEquals(clientres, RequestBody.DEFAULT_CLIENT_RETURN_STR);
    }

    Assert.assertTrue(serverConnectProcessor.isConnected());
    Assert.assertEquals(1, serverConnectProcessor.getConnectTimes());
    Assert.assertEquals(invokeTimes, serverUserProcessor.getInvokeTimes());
}
 
Example #18
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 #19
Source File: RpcClientRemoting.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
/**
 * Get connection and set init invokeContext if invokeContext not {@code null}
 *
 * @param url target url
 * @param invokeContext invoke context to set
 * @return connection
 */
protected Connection getConnectionAndInitInvokeContext(Url url, InvokeContext invokeContext)
                                                                                            throws RemotingException,
                                                                                            InterruptedException {
    long start = System.currentTimeMillis();
    Connection conn;
    try {
        conn = this.connectionManager.getAndCreateIfAbsent(url);
    } finally {
        if (null != invokeContext) {
            invokeContext.putIfAbsent(InvokeContext.CLIENT_CONN_CREATETIME,
                (System.currentTimeMillis() - start));
        }
    }
    return conn;
}
 
Example #20
Source File: BasicUsageDemoByJunit.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerSyncUsingConnection1() throws Exception {
    for (int i = 0; i < invokeTimes; i++) {
        RequestBody req1 = new RequestBody(1, RequestBody.DEFAULT_CLIENT_STR);
        String serverres = (String) client.invokeSync(addr, req1, 1000);
        Assert.assertEquals(serverres, RequestBody.DEFAULT_SERVER_RETURN_STR);

        Assert.assertNotNull(serverConnectProcessor.getConnection());
        Connection serverConn = serverConnectProcessor.getConnection();
        RequestBody req = new RequestBody(1, RequestBody.DEFAULT_SERVER_STR);
        String clientres = (String) server.getRpcServer().invokeSync(serverConn, req, 1000);
        Assert.assertEquals(clientres, RequestBody.DEFAULT_CLIENT_RETURN_STR);
    }

    Assert.assertTrue(serverConnectProcessor.isConnected());
    Assert.assertEquals(1, serverConnectProcessor.getConnectTimes());
    Assert.assertEquals(invokeTimes, serverUserProcessor.getInvokeTimes());
}
 
Example #21
Source File: NotifyDataSyncHandler.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
protected void fetchSyncData(Connection connection, NotifyDataSyncRequest request) {
    String dataInfoId = request.getDataInfoId();
    String dataCenter = request.getDataCenter();
    Datum datum = datumCache.get(dataCenter, dataInfoId);
    Long version = (datum == null) ? null : datum.getVersion();
    Long requestVersion = request.getVersion();

    if (version == null || requestVersion == 0L || version < requestVersion) {
        LOGGER.info(
            "[NotifyDataSyncProcessor] begin get sync data, currentVersion={},request={}",
            version, request);
        getSyncDataHandler.syncData(new SyncDataCallback(getSyncDataHandler, connection,
            new SyncDataRequest(dataInfoId, dataCenter, version, request.getDataSourceType()),
            dataChangeEventCenter));
    } else {
        LOGGER.info(
            "[NotifyDataSyncHandler] not need to sync data, currentVersion={},request={}",
            version, request);
    }
}
 
Example #22
Source File: BasicUsageTest.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerSyncUsingConnection1() throws Exception {
    for (int i = 0; i < invokeTimes; i++) {
        RequestBody req1 = new RequestBody(1, RequestBody.DEFAULT_CLIENT_STR);
        String serverres = (String) client.invokeSync(addr, req1, 1000);
        Assert.assertEquals(serverres, RequestBody.DEFAULT_SERVER_RETURN_STR);

        Assert.assertNotNull(serverConnectProcessor.getConnection());
        Connection serverConn = serverConnectProcessor.getConnection();
        RequestBody req = new RequestBody(1, RequestBody.DEFAULT_SERVER_STR);
        String clientres = (String) server.getRpcServer().invokeSync(serverConn, req, 1000);
        Assert.assertEquals(clientres, RequestBody.DEFAULT_CLIENT_RETURN_STR);
    }

    Assert.assertTrue(serverConnectProcessor.isConnected());
    Assert.assertEquals(1, serverConnectProcessor.getConnectTimes());
    Assert.assertEquals(invokeTimes, serverUserProcessor.getInvokeTimes());
}
 
Example #23
Source File: DataServerChangeEventHandler.java    From sofa-registry with Apache License 2.0 5 votes vote down vote up
/**
 * remove dataCenter, and close connections of dataServers in this dataCenter
 *
 * @param dataCenter
 */
private void removeDataCenter(String dataCenter) {
    DataServerNodeFactory.getDataServerNodes(dataCenter).values().stream().map(DataServerNode::getConnection)
            .filter(connection -> connection != null && connection.isFine()).forEach(Connection::close);
    DataServerNodeFactory.remove(dataCenter);
    LOGGER.info("[DataServerChangeEventHandler] remove connections of dataCenter : {}", dataCenter);
}
 
Example #24
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 #25
Source File: SessionServerNotifier.java    From sofa-registry with Apache License 2.0 5 votes vote down vote up
@Override
public void notify(Datum datum, Long lastVersion) {
    DataChangeRequest request = new DataChangeRequest(datum.getDataInfoId(),
        datum.getDataCenter(), datum.getVersion());
    List<Connection> connections = sessionServerConnectionFactory.getSessionConnections();
    for (Connection connection : connections) {
        doNotify(new NotifyCallback(connection, request));
    }
}
 
Example #26
Source File: RpcConnectionManagerTest.java    From sofa-bolt with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveConnWithSpecifiedPoolkey() {
    Connection conn1 = getAConn();
    conn1.addPoolKey("hehe");
    Connection conn2 = getAConn();
    conn2.addPoolKey("hehe");
    cm.add(conn1);
    cm.add(conn2);
    Assert.assertEquals(2, cm.count(poolKey));
    cm.remove(conn1, poolKey);
    Assert.assertEquals(1, cm.count(poolKey));
}
 
Example #27
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 #28
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 #29
Source File: ConnectionUtil.java    From sofa-bolt with Apache License 2.0 5 votes vote down vote up
public static String removeIdPoolKeyMapping(Integer id, Channel channel) {
    Connection connection = getConnectionFromChannel(channel);
    if (connection != null) {
        return connection.removeIdPoolKeyMapping(id);
    }

    return null;
}
 
Example #30
Source File: RemotingUtilTest.java    From sofa-bolt with Apache License 2.0 5 votes vote down vote up
/**
 * parse channel to get ip (format [ip])
 */
@Test
public void testParseRemoteHostIp() {
    Connection conn;
    try {
        parser.initUrlArgs(connAddress);
        conn = client.getConnection(connAddress, 1000);
        Channel channel = conn.getChannel();
        String res = RemotingUtil.parseRemoteIP(channel);
        Assert.assertEquals(localIP, res);
    } catch (Exception e) {
        Assert.assertFalse(true);
    }
}