Search in sources :

Example 11 with HostPort

use of rpc.turbo.config.HostPort in project turbo-rpc by hank-whu.

the class App method setConnect.

/**
 * 建立连接,推荐使用
 *
 * @param serverWithWeight
 *            服务提供方地址和权重
 * @throws Exception
 */
public void setConnect(Map<HostPort, Integer> serverWithWeight) throws Exception {
    if (serverWithWeight == null || serverWithWeight.size() == 0) {
        return;
    }
    if (isCloseing) {
        return;
    }
    tryStartDemoJob();
    AtomicBoolean changed = new AtomicBoolean(false);
    // 未建立连接的建立连接
    appForkJoinPool.submit(() -> {
        // 
        serverWithWeight.entrySet().stream().parallel().filter(// 过滤掉已连接上的
        kv -> !activeMap.containsKey(kv.getKey())).forEach(kv -> {
            if (isCloseing) {
                return;
            }
            changed.set(true);
            setConnect(kv.getKey(), kv.getValue());
        });
    }).get();
    // 删除多余的连接
    appForkJoinPool.submit(() -> {
        // 
        activeMap.entrySet().stream().parallel().forEach(kv -> {
            if (isCloseing) {
                return;
            }
            HostPort serverAddress = kv.getKey();
            if (!serverWithWeight.containsKey(serverAddress)) {
                changed.set(true);
                ConnectorContext context = activeMap.remove(serverAddress);
                try {
                    context.close();
                } catch (IOException e) {
                    if (logger.isWarnEnabled()) {
                        logger.warn(serverAddress + "关闭失败", e);
                    }
                }
            }
        });
    }).get();
    // 删除多余的连接
    appForkJoinPool.submit(() -> {
        // 
        zombieMap.entrySet().stream().parallel().forEach(kv -> {
            if (isCloseing) {
                return;
            }
            changed.set(true);
            HostPort serverAddress = kv.getKey();
            if (!serverWithWeight.containsKey(serverAddress)) {
                ConnectorContext context = zombieMap.remove(serverAddress);
                try {
                    context.close();
                } catch (IOException e) {
                    if (logger.isWarnEnabled()) {
                        logger.warn(serverAddress + "关闭失败", e);
                    }
                }
            }
        });
    }).get();
    if (changed.get()) {
        Collection<ConnectorContext> connectors = activeMap.values();
        int length = methodRouterMap.size();
        for (int i = 0; i < length; i++) {
            // 重置方法路由
            MethodRouter router = methodRouterMap.get(i);
            router.setConnectors(connectors);
        }
    }
}
Also used : ConcurrentArrayList(rpc.turbo.util.concurrent.ConcurrentArrayList) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) Protocol(rpc.turbo.config.server.Protocol) HostPort(rpc.turbo.config.HostPort) AppConfig(rpc.turbo.config.client.AppConfig) RemoteContext(rpc.turbo.common.RemoteContext) Weightable(rpc.turbo.loadbalance.Weightable) Map(java.util.Map) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) RemoteException(rpc.turbo.remote.RemoteException) RpcClientFilter(rpc.turbo.filter.RpcClientFilter) Method(java.lang.reflect.Method) TurboConnectService(rpc.turbo.common.TurboConnectService) Invoker(rpc.turbo.invoke.Invoker) EventLoopGroup(io.netty.channel.EventLoopGroup) TurboService(rpc.turbo.annotation.TurboService) ConcurrentIntToObjectArrayMap(rpc.turbo.util.concurrent.ConcurrentIntToObjectArrayMap) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MethodParam(rpc.turbo.param.MethodParam) IOException(java.io.IOException) InvokeException(rpc.turbo.invoke.InvokeException) Collectors(java.util.stream.Collectors) LoadBalanceFactory(rpc.turbo.loadbalance.LoadBalanceFactory) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) InvokerUtils(rpc.turbo.invoke.InvokerUtils) Stream(java.util.stream.Stream) ForkJoinPool(java.util.concurrent.ForkJoinPool) Closeable(java.io.Closeable) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HostPort(rpc.turbo.config.HostPort) IOException(java.io.IOException)

Example 12 with HostPort

use of rpc.turbo.config.HostPort in project turbo-rpc by hank-whu.

the class NettyClientConnector method connect.

void connect() throws InterruptedException {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup);
    // bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    if (eventLoopGroup instanceof EpollEventLoopGroup) {
        bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);
        bootstrap.channel(EpollSocketChannel.class);
    } else if (eventLoopGroup instanceof NioEventLoopGroup) {
        bootstrap.channel(NioSocketChannel.class);
    }
    bootstrap.handler(new TurboChannelInitializer(serializer));
    Channel[] newChannels = new Channel[connectCount];
    for (int i = 0; i < connectCount; i++) {
        newChannels[i] = bootstrap.connect(serverAddress.host, serverAddress.port).sync().channel();
        if (logger.isInfoEnabled()) {
            logger.info(serverAddress + " connect " + i + "/" + connectCount);
        }
    }
    InetSocketAddress insocket = (InetSocketAddress) newChannels[0].localAddress();
    clientAddress = new HostPort(insocket.getAddress().getHostAddress(), 0);
    Channel[] old = channels;
    channels = newChannels;
    if (old != null) {
        for (int i = 0; i < old.length; i++) {
            try {
                old[i].close();
            } catch (Exception e) {
                if (logger.isWarnEnabled()) {
                    logger.warn("关闭出错", e);
                }
            }
        }
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) InetSocketAddress(java.net.InetSocketAddress) TurboChannelInitializer(rpc.turbo.transport.client.handler.TurboChannelInitializer) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) HostPort(rpc.turbo.config.HostPort) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) IOException(java.io.IOException)

Example 13 with HostPort

use of rpc.turbo.config.HostPort in project turbo-rpc by hank-whu.

the class RestHttResponseEncoder method doResponseFilter.

private void doResponseFilter(ChannelHandlerContext ctx, FullHttpRequest request, FullHttpResponse response, Invoker<CompletableFuture<?>> invoker, Throwable throwable) {
    final int filterLength = filters.size();
    if (filterLength == 0) {
        return;
    }
    if (clientAddress == null) {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        clientAddress = new HostPort(insocket.getAddress().getHostAddress(), 0);
    }
    if (serverAddress == null) {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().localAddress();
        serverAddress = new HostPort(insocket.getAddress().getHostAddress(), insocket.getPort());
    }
    RemoteContext.setServerAddress(serverAddress);
    RemoteContext.setClientAddress(clientAddress);
    if (invoker != null) {
        RemoteContext.setRemoteMethod(invoker.getMethod());
        RemoteContext.setServiceMethodName(invokerFactory.getServiceMethodName(invoker.getServiceId()));
    } else {
        RemoteContext.setRemoteMethod(null);
        RemoteContext.setServiceMethodName(null);
    }
    if (response.status() == HttpResponseStatus.OK) {
        for (int i = 0; i < filterLength; i++) {
            RestServerFilter filter = filters.get(i);
            filter.onSend(request, response);
        }
    } else {
        for (int i = 0; i < filterLength; i++) {
            RestServerFilter filter = filters.get(i);
            filter.onError(request, response, throwable);
        }
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) HostPort(rpc.turbo.config.HostPort) RestServerFilter(rpc.turbo.filter.RestServerFilter)

Example 14 with HostPort

use of rpc.turbo.config.HostPort in project turbo-rpc by hank-whu.

the class NettyRestHandler method channelActive.

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    super.channelActive(ctx);
    if (logger.isInfoEnabled()) {
        logger.info("channelActive: " + ctx.channel());
    }
    InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
    clientAddress = new HostPort(insocket.getAddress().getHostAddress(), 0);
    insocket = (InetSocketAddress) ctx.channel().localAddress();
    serverAddress = new HostPort(insocket.getAddress().getHostAddress(), insocket.getPort());
}
Also used : InetSocketAddress(java.net.InetSocketAddress) HostPort(rpc.turbo.config.HostPort)

Aggregations

HostPort (rpc.turbo.config.HostPort)14 List (java.util.List)6 Collectors (java.util.stream.Collectors)6 IOException (java.io.IOException)5 InetSocketAddress (java.net.InetSocketAddress)4 Config (com.typesafe.config.Config)3 Log (org.apache.commons.logging.Log)3 LogFactory (org.apache.commons.logging.LogFactory)3 TurboService (rpc.turbo.annotation.TurboService)3 ConfigUtils.getStringOrElse (rpc.turbo.config.ConfigUtils.getStringOrElse)3 Protocol (rpc.turbo.config.server.Protocol)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Map (java.util.Map)2 Objects (java.util.Objects)2 ConcurrentMap (java.util.concurrent.ConcurrentMap)2 ExecutionException (java.util.concurrent.ExecutionException)2 RetryPolicy (org.apache.curator.RetryPolicy)2 CuratorFramework (org.apache.curator.framework.CuratorFramework)2 CuratorFrameworkFactory (org.apache.curator.framework.CuratorFrameworkFactory)2 PathChildrenCache (org.apache.curator.framework.recipes.cache.PathChildrenCache)2