HDFS之RPC(3) 代码

HDFS RPC处理性能提升之IBR(增量块汇报)的延时批处理 文章目录前言HDFS DataNode高频度增量块汇报行为HDFS NameNode同步IBR处理行为 前言 众所周知,HDFS NameNode内部的单一锁设计,使得这个锁显得极为的“重“。这里的重不仅仅说它很重要,而是说持有这个锁需要付出的代价很高。每个请求需要拿到这个锁,然后让NN 去处理这个请求,这里面就包含了很激烈的锁竞争。因此一旦说NN的这个锁被一个大的写操作(比如大目录的删除)持有... 阅读详情

1.RPC.getProxy与Client.call

在IPC发生之前,客户端需要通过RPC.getProxy获得一个IPC接口实例,当不需要该接口实例时,必须通过RPC.stopProxy释放资源。

client可以通过RPC提供的getProxy和waitForProxy两种方法得到,以getProxy的具体实现为例。

RPC.getProxy有3中重载方法,较复杂的方法中参数如下:

  • protocol
  • clientVersion
  • addr
  • conf
  • factory
  • rpcTimeout
  • connectionRetryPolicy
  • fallbackToSimpleAuth

这些参数表明了接口对象、接口版本、地址信息、客户端配置、创建不同套接字的工厂类等。

RPC.getProxy直接调用了RPC.getProtocolProxy方法,getProtocolProxy方法如下:

   public static <T> ProtocolProxy<T> getProtocolProxy(Class<T> protocol,
                                long clientVersion,
                                InetSocketAddress addr,
                                UserGroupInformation ticket,
                                Configuration conf,
                                SocketFactory factory,
                                int rpcTimeout,
                                RetryPolicy connectionRetryPolicy,
                                AtomicBoolean fallbackToSimpleAuth)
       throws IOException {
    if (UserGroupInformation.isSecurityEnabled()) {
      SaslRpcServer.init(conf);
    }
    return getProtocolEngine(protocol, conf).getProxy(protocol, clientVersion,
        addr, ticket, conf, factory, rpcTimeout, connectionRetryPolicy,
        fallbackToSimpleAuth);
  }

RPC类提供了getProtocolEngine类方法用于适配RPC框架当前使用的序列化引擎,以及getProtocolEngine用于获取序列化引擎对象。

上述源码中在获取代理对象时,会先调用getProtocolEngine(protocol, conf),然后调用RpcEngine.getProxy执行构造Proxy对象。Hadoop2.0之后支持protocol buffer序列化,所以在原Hadoop RPC的基础上进行了修改,提出一个RpcEngine接口,以支持第三方序列化方法,hadoop本身只实现了protocol 和 Writable序列化的engine。

我们进一步看序列化引擎的源码:

  static synchronized RpcEngine getProtocolEngine(Class<?> protocol, Configuration conf) {
    RpcEngine engine = PROTOCOL_ENGINES.get(protocol);
    if (engine == null) {
      // 默认 WritableRpcEngine.class 引擎
      Class<?> impl = conf.getClass(ENGINE_PROP+"."+protocol.getName(),
                                    WritableRpcEngine.class);
      engine = (RpcEngine)ReflectionUtils.newInstance(impl, conf);
      PROTOCOL_ENGINES.put(protocol, engine);
    }
    return engine;
  }

可以看出,hadoop默认使用WritableRpcEngine引擎。获得引擎后然后调用对应RpcEngine的getProxy方法,这里以WritableRPCEngine为例。

  public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion,
                         InetSocketAddress addr, UserGroupInformation ticket,
                         Configuration conf, SocketFactory factory,
                         int rpcTimeout, RetryPolicy connectionRetryPolicy,
                         AtomicBoolean fallbackToSimpleAuth)
    throws IOException {    

    if (connectionRetryPolicy != null) {
      throw new UnsupportedOperationException("Not supported: connectionRetryPolicy=" + connectionRetryPolicy);
    }

    // 这里才调用到原生的代理
    T proxy = (T) Proxy.newProxyInstance(protocol.getClassLoader(),
        new Class[] { protocol }, new WritableRpcEngine.Invoker(protocol, addr, ticket, conf,
            factory, rpcTimeout, fallbackToSimpleAuth));
    return new ProtocolProxy<T>(protocol, proxy, true);
  }

Proxy实例化时传进去的InvocationHandler的实现类是WritableRpcEngine的内部类Invoker。
当client端通过Proxy的实例化对象调用协议的相关接口时(即demo中proxy.hello(“didi”)),会调用WritableRpcEngine.Invoker中的invoke方法,代码如下:

private static class Invoker implements RpcInvocationHandler {
    private Client.ConnectionId remoteId;
    private Client client;
    private boolean isClosed = false;
    private final AtomicBoolean fallbackToSimpleAuth;

    // 构造器
    public Invoker(Class<?> protocol, InetSocketAddress address, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout, AtomicBoolean fallbackToSimpleAuth) throws IOException {
      this.remoteId = Client.ConnectionId.getConnectionId(address, protocol, ticket, rpcTimeout, conf);
      this.client = CLIENTS.getClient(conf, factory);
      this.fallbackToSimpleAuth = fallbackToSimpleAuth;
    }

    // 执行的invoke方法
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {	
      ...
      ObjectWritable value;
      try {
        value = (ObjectWritable)
          client.call(RPC.RpcKind.RPC_WRITABLE, new WritableRpcEngine.Invocation(method, args), remoteId, fallbackToSimpleAuth);
      } finally {
        if (traceScope != null) traceScope.close();
      }
      ...
      return value.get();
    }
    ...
}

在构造器中,client是在Invoker的构造方法中实例化的。
在invoke方法中,这里调用了Client类的call方法。其中上述 new WritableRpcEngine.Invocation(method, args)实现了Writable接口,这里的作用是将method 和 args 进行序列化。
call的具体实现使用的是Client类中的call方法,如下:

public Writable call(RpcKind rpcKind, Writable rpcRequest, Client.ConnectionId remoteId, int serviceClass, AtomicBoolean fallbackToSimpleAuth) throws IOException {
    // 将远程调用信息封装成一个Client.Call对象 每个Call都有一个唯一的callId
    Client.Call call = this.createCall(rpcKind, rpcRequest);
    // 根据remoteId创建一个connection对象,并将call放到该对象的hashtable calls中
    Client.Connection connection = this.getConnection(remoteId, call, serviceClass, fallbackToSimpleAuth);
    // 下边会有发送至server的代码,见后分析
    ...
}

在call方法中先将远程调用信息封装成一个Client.Call对象,然后通过getConnection得到connection对象,将封装好的call对象放入connection对象的hashtable calls中

private Connection getConnection(ConnectionId remoteId,
      Call call, int serviceClass, AtomicBoolean fallbackToSimpleAuth)
      throws IOException {
    if (!running.get()) {
      // the client is stopped
      throw new IOException("The client is stopped");
    }
    Connection connection;
    do {
      synchronized (connections) {
        connection = connections.get(remoteId);
        // 先从 connections中查找是否存在,不存在则创建
        if (connection == null) {
          // 这里new 只是对一些相关属性进行赋值,并没有真正的建立连接
          connection = new Connection(remoteId, serviceClass);
          connections.put(remoteId, connection);
        }
      }
    } while (!connection.addCall(call));
    // 建立连接
    connection.setupIOstreams(fallbackToSimpleAuth);
    return connection;
  }

在setupIOstreams中建立连接,代码如下:

 private synchronized void setupIOstreams(
        AtomicBoolean fallbackToSimpleAuth) {
      if (socket != null || shouldCloseConnection.get()) {
        return;
      } 
      try {
        if (LOG.isDebugEnabled()) {
          LOG.debug("Connecting to "+server);
        }
        if (Trace.isTracing()) {
          Trace.addTimelineAnnotation("IPC client connecting to " + server);
        }
        short numRetries = 0;
        Random rand = null;
        while (true) {
          // 建立socket进行连接  可见client是用socket进行通信
          setupConnection();
          InputStream inStream = NetUtils.getInputStream(socket);
          OutputStream outStream = NetUtils.getOutputStream(socket);
          writeConnectionHeader(outStream);
          if (authProtocol == AuthProtocol.SASL) {
            final InputStream in2 = inStream;
            final OutputStream out2 = outStream;
            UserGroupInformation ticket = remoteId.getTicket();
            if (ticket.getRealUser() != null) {
              ticket = ticket.getRealUser();
            }
            try {
              authMethod = ticket
                  .doAs(new PrivilegedExceptionAction<AuthMethod>() {
                    @Override
                    public AuthMethod run()
                        throws IOException, InterruptedException {
                      return setupSaslConnection(in2, out2);
                    }
                  });
            } catch (Exception ex) {
              authMethod = saslRpcClient.getAuthMethod();
              if (rand == null) {
                rand = new Random();
              }
              handleSaslConnectionFailure(numRetries++, maxRetriesOnSasl, ex,
                  rand, ticket);
              continue;
            }
            if (authMethod != AuthMethod.SIMPLE) {
              // Sasl connect is successful. Let's set up Sasl i/o streams.
              ...
          }
        
          if (doPing) {
            inStream = new PingInputStream(inStream);
          }
          this.in = new DataInputStream(new BufferedInputStream(inStream));

          // SASL may have already buffered the stream
          if (!(outStream instanceof BufferedOutputStream)) {
            outStream = new BufferedOutputStream(outStream);
          }
          this.out = new DataOutputStream(outStream);
          
          // 将内容写入消息
          writeConnectionContext(remoteId, authMethod);

          // update last activity time
          touch();

          if (Trace.isTracing()) {
            Trace.addTimelineAnnotation("IPC client connected to " + server);
          }

          // start the receiver thread after the socket connection has been set up
          start();  // 启动connection线程,等待接受server的response
          return;
        }
      } catch (Throwable t) {
        if (t instanceof IOException) {
          markClosed((IOException)t);
        } else {
          markClosed(new IOException("Couldn't set up IO streams", t));
        }
        close();
      }
    }

上述代码中,通过setupConnection方法进行socket连接。

 private synchronized void setupConnection() throws IOException {
      short ioFailures = 0;
      short timeoutFailures = 0;
      while (true) {
        try {
          // 创建一个网络socket
          this.socket = socketFactory.createSocket();
          this.socket.setTcpNoDelay(tcpNoDelay);
          this.socket.setKeepAlive(true);
          
          /*
           * Bind the socket to the host specified in the principal name of the
           * client, to ensure Server matching address of the client connection
           * to host name in principal passed.
           */
          UserGroupInformation ticket = remoteId.getTicket();
          if (ticket != null && ticket.hasKerberosCredentials()) {
            KerberosInfo krbInfo = 
              remoteId.getProtocol().getAnnotation(KerberosInfo.class);
            if (krbInfo != null && krbInfo.clientPrincipal() != null) {
              String host = 
                SecurityUtil.getHostFromPrincipal(remoteId.getTicket().getUserName());
              
              // If host name is a valid local address then bind socket to it
              InetAddress localAddr = NetUtils.getLocalInetAddress(host);
              if (localAddr != null) {
                this.socket.bind(new InetSocketAddress(localAddr, 0));
              }
            }
          }
          
          NetUtils.connect(this.socket, server, connectionTimeout);
          this.socket.setSoTimeout(soTimeout);
          return;
        } catch (ConnectTimeoutException toe) {
          /* Check for an address change and update the local reference.
           * Reset the failure counter if the address was changed
           */
          if (updateAddress()) {
            timeoutFailures = ioFailures = 0;
          }
          handleConnectionTimeout(timeoutFailures++,
              maxRetriesOnSocketTimeouts, toe);
        } catch (IOException ie) {
          if (updateAddress()) {
            timeoutFailures = ioFailures = 0;
          }
          handleConnectionFailure(ioFailures++, ie);
        }
      }
    }

建立连接之后,启动connection线程,运行run方法,等待server端的response。代码:

public void run() {
  if (LOG.isDebugEnabled())
    LOG.debug(getName() + ": starting, having connections " 
        + connections.size());

  try {
    while (waitForWork()) {//wait here for work - read or close connection
      receiveRpcResponse();
    }
  } catch (Throwable t) {
    // This truly is unexpected, since we catch IOException in receiveResponse
    // -- this is only to be really sure that we don't leave a client hanging
    // forever.
    LOG.warn("Unexpected error reading responses on connection " + this, t);
    markClosed(new IOException("Error reading responses", t));
  }
  
  close();
  
  if (LOG.isDebugEnabled())
    LOG.debug(getName() + ": stopped, remaining connections "
        + connections.size());
}

getConnection逻辑已经初步完结,现在回到call代码中,继续分析其代码,下面的关键代码是connection.sendRpcRequest(call),发送call对象到server端,并进入阻塞状态等待server的response。代码如下:

public Writable call(RPC.RpcKind rpcKind, Writable rpcRequest, ConnectionId remoteId, int serviceClass, AtomicBoolean fallbackToSimpleAuth) throws IOException {
    final Call call = createCall(rpcKind, rpcRequest);
    Connection connection = getConnection(remoteId, call, serviceClass, fallbackToSimpleAuth);
    try {
      // 将远程调用信息发送给server端
      connection.sendRpcRequest(call);                 // send the rpc request
    } catch (RejectedExecutionException e) {
      throw new IOException("connection has been closed", e);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new IOException(e);
    }

    synchronized (call) {
      // 判断call是否完成,等待server端notify
      while (!call.done) {
        try {
          // 当前线程blocking住,
          // 等待Connection线程中receiveRpcResponse调用call.notify
          call.wait();                           // wait for the result
        } catch (InterruptedException ie) {
          Thread.currentThread().interrupt();
          throw new InterruptedIOException("Call interrupted");
        }
      }

      if (call.error != null) {
        if (call.error instanceof RemoteException) {
          call.error.fillInStackTrace();
          throw call.error;
        } else { // local exception
          InetSocketAddress address = connection.getRemoteAddress();
          throw NetUtils.wrapException(address.getHostName(),
                  address.getPort(),
                  NetUtils.getHostname(),
                  0,
                  call.error);
        }
      } else {
        // 得到server结果
        return call.getRpcResponse();
      }
    }
  }
 public void sendRpcRequest(final Call call)
        throws InterruptedException, IOException {
      if (shouldCloseConnection.get()) {
        return;
      }

      // Serialize the call to be sent. This is done from the actual
      // caller thread, rather than the sendParamsExecutor thread,
      
      // so that if the serialization throws an error, it is reported
      // properly. This also parallelizes the serialization.
      //
      // Format of a call on the wire:
      // 0) Length of rest below (1 + 2)
      // 1) RpcRequestHeader  - is serialized Delimited hence contains length
      // 2) RpcRequest
      //
      // Items '1' and '2' are prepared here. 
      final DataOutputBuffer d = new DataOutputBuffer();
      RpcRequestHeaderProto header = ProtoUtil.makeRpcRequestHeader(
          call.rpcKind, OperationProto.RPC_FINAL_PACKET, call.id, call.retry,
          clientId);
      header.writeDelimitedTo(d);
      call.rpcRequest.write(d);

      synchronized (sendRpcRequestLock) {
        Future<?> senderFuture = sendParamsExecutor.submit(new Runnable() {
          @Override
          public void run() {
            try {
              synchronized (Connection.this.out) {
                if (shouldCloseConnection.get()) {
                  return;
                }
                
                if (LOG.isDebugEnabled())
                  LOG.debug(getName() + " sending #" + call.id);
         
                byte[] data = d.getData();
                int totalLength = d.getLength();
                out.writeInt(totalLength); // Total Length
                out.write(data, 0, totalLength);// RpcRequestHeader + RpcRequest
                out.flush();
              }
            } catch (IOException e) {
              // exception at this point would leave the connection in an
              // unrecoverable state (eg half a call left on the wire).
              // So, close the connection, killing any outstanding calls
              markClosed(e);
            } finally {
              //the buffer is just an in-memory buffer, but it is still polite to
              // close early
              IOUtils.closeStream(d);
            }
          }
        });
      
        try {
          // 等待call发送完毕之后才退出该方法,回到call方法中继续执行
          senderFuture.get();
        } catch (ExecutionException e) {
          Throwable cause = e.getCause();
          
          // cause should only be a RuntimeException as the Runnable above
          // catches IOException
          if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
          } else {
            throw new RuntimeException("unexpected checked exception", cause);
          }
        }
      }
    }

接下来分析Server代码。


2. Server

先见 http://bigdatadecode.club/Hadoop%20RPC%20%E8%A7%A3%E6%9E%90.html
后续补充

Hadoop学习<四>--HDFS的RPC通信原理总结 这里先写下自己学习RPC的笔记总结,下面将详细介绍学习过程: RPC(remote procedure call)   不同java进程间的对象方法的调用。   一方称作服务端(server),一方称作客户端(client)。   server端提供对象,供客户端调用的,被调用的对象的方法的执行发生在server端。      RPC是hadoop框架运行的基础。 通 阅读详情

相关推荐

记录一次HDFS RPC返回Response过程慢导致的性能问题

文章目录前言NameNode请求处理慢的场景RPC返回response的Handler处理慢问题HDFS RPC call异步response改造 前言 众所周知,在HDFS NameNode中,一直都有一个老生常谈的难题就是其扩展性的问题,而很多时候我们说HDFS的扩展性问题时我们很多时候都在谈的点在于里面全局锁的问题。一个很通常的场景是NameNode在高并发请求处理下存在着激烈的锁竞争,进而使得用户感觉到他们的请求被处理的有点慢。不过本文笔者不聊关于全局锁优化的问题,最近笔者遇到了另外一种NameN

走在前往架构师的路上 3万+

聊聊hdfs中的rpc问题

hdfs中的rpc问题

luo981695830的博客 2118

RPC和HDFS文件读写(下载上传)过程

1 RPC RPC——远程过程调用协议,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议。RPC协议假定 某些传输协议的存在,如TCP或UDP,为通信程序之间携带信息数据。在OSI网络通信模型中,RPC跨越了传输层和应用层。RPC 使得开发包括网络分布式多程序在内的应用程序更加容易。 RPC采用客户机/服务器模式。请求程序就是一个客

3593

HDFS之RPC(1) 概述

本文介绍了RPC基本原理,RPC的java实现,以及分析了hadoopRPC的实现原理

王小禾 1953

Hadoop笔记三之Hdfs体系架构及各节点之间的Rpc通信

前言:    Rpc协议就是Server实现一个声明了很多方法的接口并对外暴露此接口,Client通过调用此接口中声明的方法向server发送信息从而实现了与server的通信。 介绍: Hdfs是分布式部署的,分为nameNode,secondaryNameNode,dataNode,DFSClient四部分,每个节点之间都遵守RPC通信协议。   一:NameNode与DataNod

ty4315的专栏 4289

Hadoop 3.x环境下可直接部署的HDFS云盘实战项目(含源码+配置+部署指南)

这个HDFS云盘系统基于Hadoop 3.x构建,开箱即用,支持文件上传、下载和目录浏览等核心云存储操作。项目提供完整的Java源码,结构清晰:src包含主逻辑,test覆盖关键路径,main定义启动入口,pom.xml管理依赖,配套README和详细部署文档说明从伪分布式到集群环境的搭建步骤、配置修改要点及常见问题解决方法。所有代码经过实际Hadoop集群验证,运行稳定,注释充分,关键流程有说明,方便理解底层HDFS交互机制。适合计算机专业学生做课程设计或毕设参考,也适合想动手实践分布式存储开发的学习者—

sat99的博客 206

HDFSRPC通信框架详解

rpc肯定依赖于socket通信,并且使用的是java NIO。读者最好对nio有一定的了解,文章中不会对相关知识作过多的介绍。还有本文中涉及到的代码大部分都是作者都整理过的,会和server源码有些许区别。

行路中 1400

R语言影像组学实战:从医学图像到预测模型的完整流程(附代码)

本文详细介绍了使用R语言进行影像组学分析的完整实战流程。从环境搭建、数据准备,到医学图像的特征提取与筛选,再到利用机器学习构建预测模型并进行评估,提供了清晰的步骤和可运行的R代码示例,帮助研究者和数据分析师掌握从医学图像到临床预测模型的核心技术。

qsc901234的博客 732

轻松使用Hadoop RPC

Hadoop RPC是Hadoop的一个重要部分,提供分布式环境下的对象调用功能,源码在org.apache.hadoop.ipc中。而HBase也几乎完全copy了这部分的源码,只是在配置项上面有所改动。关于Hadoop RPC的机制分析和源码解读,网上已经有许多资料,一搜一大把,这里就不在描述了。本文通过一个小例子,介绍如何调用Hadoop RPC

欢迎朋友,我是一名十多年开发经验的新手,希望多多指教。 690

1.深入浅出:理解三极管截止、放大和饱和状态!——参考《模拟电子技术基础》清华大学华成英主讲

幼儿园水平理解三极管截止、放大和饱和状态!书上看不懂,听课听不懂的过来! 绕不开的三极管结构 以NPN为例,晶体三极管的结构,这是很多人不想看的,但是确实是非常重要的!不看结构是理解不了工作原理的! (这样记忆:N是negative,负,代表多子为电子;P是positive,正,代表多子为空穴) 注意观察三极管的结构,有助于理解工作时的状态。 两张图结合起来看,略作解释: 1.图中空心为空穴带正...

Hardware_harder的博客 4万+

斯坦福HumanPlus机器人核心技术解析:从HST强化学习框架到HIT模仿学习的实现路径

本文深入解析了斯坦福HumanPlus人形机器人的核心技术实现路径。其核心在于HST强化学习框架与HIT模仿学习架构的协同:HST作为“小脑”,通过rsl_rl框架在仿真中训练稳健的低级运动控制;HIT作为“大脑”,基于改进的Transformer架构学习高级任务规划。文章详细拆解了从算法原理、代码实现到硬件部署的全流程,为复现这一前沿机器人系统提供了实战指南。

weixin_29082143的博客 280

hadoop实现原理 (三) 远程过程调用

分析hadoop源码,梳理远程过程调用的原理

厚积薄发 786

STM32 HAL库定时器中断里读编码器速度准吗?聊聊MG310电机的测速与防溢出处理

本文探讨了STM32 HAL库在定时器中断中读取编码器速度的精度问题,特别针对MG310电机的测速与防溢出处理提供了解决方案。通过对比定时中断法和编码器模式的性能,揭示了硬件编码器接口在降低误差和CPU占用率方面的优势,并详细介绍了CubeMX配置技巧和防溢出处理的工程实践。

weixin_28720767的博客 400

hadoop RPC详解(3)--hdfs rpc server代码分析

通过前面hadoop rpc demo我们可以看出主要代码是Server 类。通过Server 类的代码分析,我们看下整个服务端的执行过程。 1.通过Listener启动SocketServer服务监听连接请求: Listener(int port) throws IOException { address = new InetSocketAddress(bindAddress, port); // Create a new server socket and set...

wflh323的专栏 483

EETI_eGTouch驱动移植及校准

一.环境 芯片:NXP IMX6Q 内核版本:4.1.15 uname:Linux myimx6ek314 4.1.15-myimx6-g5d588fa6-dirty #4 SMP PREEMPT Tue Nov 17 17:26:34 CST 2020 armv7l armv7l armv7l GNU/Linux 二.官方《EETI_eGTouch_Linux_Programming_Guide_v2.5l.pdf》文档勘误 HID_MULTITOUCH =Y or N(官方文档设置为M): 正确设置H

Garden的博客 4332

如何使你的直流电机闭环?(PID讲解)

看了看很多大佬写的PID讲解很全面也很复杂,实在是不适合很多萌新入坑,所以想按自己的理解写一篇通俗易懂的PID算法讲解

a2001444的博客 1万+

Hadoop3.2.x HDFS源码分析目录汇总 [完结]

Hadoop3.2.0 源码编译 [一] MAC版本: Hadoop3.2.0 源码编译 [ 二 ] Hadoop3.2.0 源码分析: SHELL启动脚本 DEBUG 模式 Hadoop3.2.0 源码分析: namenode 启动 Hadoop3.2.0 源码分析: datanode 启动 Hadoop3.2.0 源码分析: ResourceManager启动 Hadoop3.2.0 源码分析: NodeManager Hadoop3.2.0 源码分析: Container 之...

张伯毅的专栏 1万+

【100%通过率】华为OD机试真题 C 实现【最多等和不相交连续子序列】【2022.11 Q4 新题】

给定一个数组,我们称其中连续的元素为连续子序列,称这些元素的和为连续子序列的和。数组中可能存在几组连续子序列,组内的连续子序列互不相交且有相同的和。求一组连续子序列,组内子序列的数目最多。输出这个数目。

MISAYAONE的博客 1万+

hadoop优化

hdfs balancer优化:参考Hdfs-13813\Hdfs-9412\HDFS-8824以及hadoop3.1代码优化hdfs balancer:将getDatanodeStorageReport和getblocks的请求发送到Namenode standby以及忽略小数据块 修改的代码如下: (1) 将日志记录模式修改为异步 Hdfs-site.xml中...

weixin_30932215的博客 262

2023年全国职业院校技能大赛 网络系统管理服务模块 Linux部分讲解

网络系统管理,Linux,服务部署,Chinaskills,2023国赛

weixin_62926639的博客 1545

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

spark 3.x Plugin Framework

背景 该文基于spark 3.0.1 spark 3.0引入了一个新的插件框架,其实这个插件在spark 2.x就已经存在了,只不过spark 3.0对该插件进行了重构。因为在之前该插件是不支持driver端的,具体可以见SPARK-29396。至于为什么引入这么一个插件 是为了更好的监控和定制一些指标,以便更好的进行spark调优。 插件功能 支持自定义的指标 用户可以写代码进行自定义指标的编写,而这些指标和spark的指标结合, 这样就能通过sinks进行收集,具体参见metrics execu

monkeyboy_tech的博客 972

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

HDFS RPC限流方案实践探索

文章目录前言HDFS RPC限流方案分级RPC queue的调参分级RPC queue的insight 前言 在前面的一篇关于分布式集群下的限流方案文章里,笔者阐述了一种在HDFS集群里的RPC限流架构。其间也提到了很多关于分布式限流架构里的关键要素,包括用户区分,分级队列的概念等等。不过上次文章更多偏向于理论原理篇,本文笔者将结合实际生产环境的特点,来给大家讲讲如何真正将限流方案实施到生产集群,并能够达到预期的效果。 HDFS RPC限流方案 这里要首先聊聊笔者目前集群所将要采用的HDFS RPC限流

走在前往架构师的路上 1384

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

基于RPC Call延时返回的HDFS异步editlog原理

文章目录前言现有HDFS的RPC正常请求处理 前言 前面文章笔者介绍过Hadoop社区为了增加内部RPC的throughput,通过延时返回response的调整来提早释放Server端的Handler资源,以此尽可能的把Handler的处理能力用在真正的RPC请求上。HDFS目前所使用的异步editlog机制正是使用了这个优化改进。这里所说的HDFS异步editlog写出并不是大家所简单的认为NameNode完全异步化写出editlog到其JournalNode服务中,然后直接返回结果给client。那

走在前往架构师的路上 1330

HDFS中RPC机制

RPC 是远程过程调用 (Remote Procedure Call),即远程调用其他虚拟机中运行的 java object。 RPC 是一种客户端/服务器模式, 那么在使用时包括服务端代码和客户端代码, 还有 我们调用的远程过程对象。 RPC调用机制,如下图 PRC cline 和 service 端必须实现同一接口! 、、、、、、运行机制、***、、、、 1、先获取 interface 接...

qq_41854797的博客 2348

RPC,HDFS,源代码解析

1.RPC 通信原理解析 1)需求: 模拟 RPC 的客户端、服务端、通信协议三者如何工作的 2)代码编写: (1)在 HDFSClient 项目基础上创建包名 com.atguigu.rpc (2)创建 RPC 协议 package com.atguigu.rpc; public interface RPCProtocol { long versionID = 666; void mkdirs(String path); } (3)创建 RP..

song_quan_的博客 232

HDFS-源码深度分析RPC机制

HDFS-源码深度分析RPC机制 一个分布式系统最重要的组件之一就是RPC协议,如何构建一套高性能的RPC协议就显得非常重要了,那么来看看HDFS的RPC协议是如何构建的吧。 1.原理剖析部分 通信流程 HDFS的RPC协议的序列化协议分为两种,第一种是Writerable,一种是Protobuf,前者是HDFS是HDFS自定义的,也是默认的序列化协议,要用Protobuf需要将参数进行包装和响应进行解析为接口返回的类型。本篇主要研究Protobuf协议,Writerable其实也是囊括在内的。 简要流程

尹忠政的博客 1613
上一篇: HDFS之RPC(2) 测试
下一篇: 补充:RPC与NIO
王小禾
博客等级 码龄11年 80粉丝 291原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值