首页 文章 精选 留言 我的

精选列表

搜索[Rust编程],共10000篇文章
优秀的个人博客,低调大师

Java并发编程实战系列10之避免活跃性危险

10.1 死锁 哲学家问题 有环 A等B,B等A 数据库往往可以检测和解决死锁//TODO JVM不行,一旦死锁只有停止重启。 下面分别介绍了几种典型的死锁情况: 10.1.1 Lock ordering Deadlocks 下面是一个经典的锁顺序死锁:两个线程用不同的顺序来获得相同的锁,如果按照锁的请求顺序来请求锁,就不会发生这种循环依赖的情况。 public class LeftRightDeadlock { private final Object left = new Object(); private final Object right = new Object(); public void leftRight() { synchronized (left) { synchronized (right) { doSomething(); } } } public void rightLeft() { synchronized (right) { synchronized (left) { doSomethingElse(); } } } void doSomething() { } void doSomethingElse() { } } 10.1.1 Dynamic Lock Order Deadlocks 下面的转账例子,如果一个线程X向Y转,而另外一个线程Y向X也转,那么就会发生死锁。 public class DynamicOrderDeadlock { // Warning: deadlock-prone! public static void transferMoney(Account fromAccount, Account toAccount, DollarAmount amount) throws InsufficientFundsException { synchronized (fromAccount) { synchronized (toAccount) { if (fromAccount.getBalance().compareTo(amount) < 0) throw new InsufficientFundsException(); else { fromAccount.debit(amount); toAccount.credit(amount); } } } } static class DollarAmount implements Comparable<DollarAmount> { // Needs implementation public DollarAmount(int amount) { } public DollarAmount add(DollarAmount d) { return null; } public DollarAmount subtract(DollarAmount d) { return null; } public int compareTo(DollarAmount dollarAmount) { return 0; } } static class Account { private DollarAmount balance; private final int acctNo; private static final AtomicInteger sequence = new AtomicInteger(); public Account() { acctNo = sequence.incrementAndGet(); } void debit(DollarAmount d) { balance = balance.subtract(d); } void credit(DollarAmount d) { balance = balance.add(d); } DollarAmount getBalance() { return balance; } int getAcctNo() { return acctNo; } } static class InsufficientFundsException extends Exception { } } 解决办法还是顺序话锁,考虑针对两种情况取hashcode然后判断if-else里面决定锁顺序。 class Helper { public void transfer() throws InsufficientFundsException { if (fromAcct.getBalance().compareTo(amount) < 0) throw new InsufficientFundsException(); else { fromAcct.debit(amount); toAcct.credit(amount); } } } int fromHash = System.identityHashCode(fromAcct); int toHash = System.identityHashCode(toAcct); if (fromHash < toHash) { synchronized (fromAcct) { synchronized (toAcct) { new Helper().transfer(); } } } else if (fromHash > toHash) { synchronized (toAcct) { synchronized (fromAcct) { new Helper().transfer(); } } } else { synchronized (tieLock) { synchronized (fromAcct) { synchronized (toAcct) { new Helper().transfer(); } } } } 10.1.3 在协作对象之间发生死锁Deadlocks Between Cooperating Objects 下面的例子setLocation和getImage都会获取两把锁,会存在两个线程按照不同的顺序获取锁的情况。 public class CooperatingDeadlock { // Warning: deadlock-prone! class Taxi { @GuardedBy("this") private Point location, destination; private final Dispatcher dispatcher; public Taxi(Dispatcher dispatcher) { this.dispatcher = dispatcher; } public synchronized Point getLocation() { return location; } public synchronized void setLocation(Point location) { this.location = location; if (location.equals(destination)) dispatcher.notifyAvailable(this); } public synchronized Point getDestination() { return destination; } public synchronized void setDestination(Point destination) { this.destination = destination; } } class Dispatcher { @GuardedBy("this") private final Set<Taxi> taxis; @GuardedBy("this") private final Set<Taxi> availableTaxis; public Dispatcher() { taxis = new HashSet<Taxi>(); availableTaxis = new HashSet<Taxi>(); } public synchronized void notifyAvailable(Taxi taxi) { availableTaxis.add(taxi); } public synchronized Image getImage() { Image image = new Image(); for (Taxi t : taxis) image.drawMarker(t.getLocation()); return image; } } class Image { public void drawMarker(Point p) { } } } 10.1.4 开放调用 减小锁的力度,锁不嵌套。 class CooperatingNoDeadlock { @ThreadSafe class Taxi { @GuardedBy("this") private Point location, destination; private final Dispatcher dispatcher; public Taxi(Dispatcher dispatcher) { this.dispatcher = dispatcher; } public synchronized Point getLocation() { return location; } public synchronized void setLocation(Point location) { boolean reachedDestination; synchronized (this) { this.location = location; reachedDestination = location.equals(destination); } if (reachedDestination) dispatcher.notifyAvailable(this); } public synchronized Point getDestination() { return destination; } public synchronized void setDestination(Point destination) { this.destination = destination; } } @ThreadSafe class Dispatcher { @GuardedBy("this") private final Set<Taxi> taxis; @GuardedBy("this") private final Set<Taxi> availableTaxis; public Dispatcher() { taxis = new HashSet<Taxi>(); availableTaxis = new HashSet<Taxi>(); } public synchronized void notifyAvailable(Taxi taxi) { availableTaxis.add(taxi); } public Image getImage() { Set<Taxi> copy; synchronized (this) { copy = new HashSet<Taxi>(taxis); } Image image = new Image(); for (Taxi t : copy) image.drawMarker(t.getLocation()); return image; } } class Image { public void drawMarker(Point p) { } } } 1.0.15 资源死锁 数据库连接池,A持有数据库D1连接,等待与D2连接,B持有D2的连接,等待与D1连接。 线程饥饿死锁,如8.1.1小节的例子。 10.2 死锁的避免与诊断 10.2.1 支持定时的锁 tryLock 10.2.2 kill -3 发信号给JVM dump线程 10.3 其他活跃性危险 10.3.1 饥饿 10.3.3 活锁Livelock 他不会阻塞线程,但是也不能继续执行,因为线程在不断的重复执行相同的操作,而且总会失败。 例如处理事务消,回滚后再次重新把任务放在队头。 又例如发送数据包,都选择1s后重试,那么总会冲突,所以可以考虑一个随机数时间间隔。

优秀的个人博客,低调大师

Java并发编程实战系列8之线程池的使用

ThreadPoolExecutor UML图: image image 8.1 在任务和执行策略之间隐形耦合 避免Thread starvation deadlock 8.2 设置线程池大小 8.3 配置ThreadPoolExecutor image 构造函数如下: public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { ... } 核心和最大池大小:如果运行的线程少于 corePoolSize,则创建新线程来处理请求(即一个Runnable实例),即使其它线程是空闲的。如果运行的线程多于 corePoolSize 而少于 maximumPoolSize,则仅当队列满时才创建新线程。 保持活动时间:如果池中当前有多于 corePoolSize 的线程,则这些多出的线程在空闲时间超过 keepAliveTime 时将会终止。 排队:如果运行的线程等于或多于 corePoolSize,则 Executor 始终首选将请求加入队列BlockingQueue,而不添加新的线程。 被拒绝的任务:当 Executor 已经关闭,或者队列已满且线程数量达到maximumPoolSize时(即线程池饱和了),请求将被拒绝。这些拒绝的策略叫做Saturation Policy,即饱和策略。包括AbortPolicy, CallerRunsPolicy, DiscardPolicy, and DiscardOldestPolicy. 另外注意: 如果运行的线程少于 corePoolSize,ThreadPoolExecutor 会始终首选创建新的线程来处理请求;注意,这时即使有空闲线程也不会重复使用(这和数据库连接池有很大差别)。 如果运行的线程等于或多于 corePoolSize,则 ThreadPoolExecutor 会将请求加入队列BlockingQueue,而不添加新的线程(这和数据库连接池也不一样)。 如果无法将请求加入队列(比如队列已满),则创建新的线程来处理请求;但是如果创建的线程数超出 maximumPoolSize,在这种情况下,请求将被拒绝。 newCachedThreadPool使用了SynchronousQueue,并且是无界的。 线程工厂ThreadFactory 8.4 扩展ThreadPoolExecutor 重写beforeExecute和afterExecute方法。 8.5 递归算法的并行化 实际就是类似Number of Islands或者N-Queens等DFS问题的一种并行处理。 串行版本如下: public class SequentialPuzzleSolver <P, M> { private final Puzzle<P, M> puzzle; private final Set<P> seen = new HashSet<P>(); public SequentialPuzzleSolver(Puzzle<P, M> puzzle) { this.puzzle = puzzle; } public List<M> solve() { P pos = puzzle.initialPosition(); return search(new PuzzleNode<P, M>(pos, null, null)); } private List<M> search(PuzzleNode<P, M> node) { if (!seen.contains(node.pos)) { seen.add(node.pos); if (puzzle.isGoal(node.pos)) return node.asMoveList(); for (M move : puzzle.legalMoves(node.pos)) { P pos = puzzle.move(node.pos, move); PuzzleNode<P, M> child = new PuzzleNode<P, M>(pos, move, node); List<M> result = search(child); if (result != null) return result; } } return null; } } 并行版本如下: public class ConcurrentPuzzleSolver <P, M> { private final Puzzle<P, M> puzzle; private final ExecutorService exec; private final ConcurrentMap<P, Boolean> seen; protected final ValueLatch<PuzzleNode<P, M>> solution = new ValueLatch<PuzzleNode<P, M>>(); public ConcurrentPuzzleSolver(Puzzle<P, M> puzzle) { this.puzzle = puzzle; this.exec = initThreadPool(); this.seen = new ConcurrentHashMap<P, Boolean>(); if (exec instanceof ThreadPoolExecutor) { ThreadPoolExecutor tpe = (ThreadPoolExecutor) exec; tpe.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); } } private ExecutorService initThreadPool() { return Executors.newCachedThreadPool(); } public List<M> solve() throws InterruptedException { try { P p = puzzle.initialPosition(); exec.execute(newTask(p, null, null)); // block until solution found PuzzleNode<P, M> solnPuzzleNode = solution.getValue(); return (solnPuzzleNode == null) ? null : solnPuzzleNode.asMoveList(); } finally { exec.shutdown(); } } protected Runnable newTask(P p, M m, PuzzleNode<P, M> n) { return new SolverTask(p, m, n); } protected class SolverTask extends PuzzleNode<P, M> implements Runnable { SolverTask(P pos, M move, PuzzleNode<P, M> prev) { super(pos, move, prev); } public void run() { if (solution.isSet() || seen.putIfAbsent(pos, true) != null) return; // already solved or seen this position if (puzzle.isGoal(pos)) solution.setValue(this); else for (M m : puzzle.legalMoves(pos)) exec.execute(newTask(puzzle.move(pos, m), m, this)); } } }

优秀的个人博客,低调大师

Java并发编程实战系列16之Java内存模型(JMM)

前面几章介绍的安全发布、同步策略的规范还有一致性,这些安全性都来自于JMM。 16.1 什么是内存模型,为什么需要它? 假设 a=3 内存模型要解决的问题是:“在什么条件下,读取a的线程可以看到这个值为3?” 如果缺少同步会有很多因素导致无法立即、甚至永远看不到一个线程的操作结果,包括 编译器中指令顺序 变量保存在寄存器而不是内存中 处理器可以乱序或者并行执行指令 缓存可能会改变将写入变量提交到主内存的次序 处理器中也有本地缓存,对其他处理器不可见 单线程中,会为了提高速度使用这些技术,但是Java语言规范要求JVM在线程中维护一种类似串行的语义:只要程序的最终结果与在严格环境中的执行结果相同,那么上述操作都是允许的。 随着处理器越来越强大,编译器也在不断的改进,通过指令重排序实现优化执行,使用成熟的全局寄存器分配算法,但是单处理器存在瓶颈,转而变为多核,提高并行性。 在多线程环境中,维护程序的串行性将导致很大的性能开销,并发程序中的线程,大多数时间各自为政,线程之间协调操作只会降低应用程序的运行速度,不会带来任何好处,只有当多个线程要共享数据时,才必须协调他们之间的操作,并且JVM依赖程序通过同步操作找出这些协调操作将何时发生。 JMM规定了JVM必须遵循一组最小的保证,保证规定了对变量的写入操作在何时将对其他线程可见。JMM需要在各个处理器体系架构中实现一份。 16.1.1 平台的内存模型 在共享内存的多处理器体系架构中,每个处理器拥有自己的缓存,并且定期的与主内存进行协调。在不同的处理器架构中提供了不同级别的缓存一致性(cache coherence)。其中一部分只提供最小的保证,即允许不同的处理器在任意时刻从同一个存储位置上看到不同的值。操作系统、编译器以及runtime需要弥补这种硬件能力与线程安全需求之间的差异。 要确保每个处理器在任意时刻都知道其他处理器在进行的工作,这将开销巨大。多数情况下,这完全没必要,可随意放宽存储一致性,换取性能的提升。存在一些特殊的指令(成为内存栅栏),当需要共享数据时,这些指令就能实现额外的存储协调保证。为了使Java开发人员无须关心不同架构上内存模型之间的差异,产生了JMM,JVM通过在适当的位置上插入内存栅栏来屏蔽JMM与底层平台内存模型之间的差异。 按照程序的顺序执行,这种乐观的串行一致性在任何一款现代多处理器架构中都不会提供这种串行一致性。当跨线程共享数据时,会出现一些奇怪的情况,除非通过使用内存栅栏来防止这种情况的发生。 16.1.2 重排序 下面的代码,4中输出都是有可能的。 public class ReorderingDemo { static int x = 0, y = 0, a = 0, b = 0; public static void main(String[] args) throws Exception { Bag bag = new HashBag(); for (int i = 0; i < 10000; i++) { x = y = a = b = 0; Thread one = new Thread() { public void run() { a = 1; x = b; } }; Thread two = new Thread() { public void run() { b = 1; y = a; } }; one.start(); two.start(); one.join(); two.join(); bag.add(x + "_" + y); } System.out.println(bag.getCount("0_1")); System.out.println(bag.getCount("1_0")); System.out.println(bag.getCount("1_1")); System.out.println(bag.getCount("0_0")); // 结果是如下的或者其他情况,证明可能发生指令重排序 // 9999 // 1 // 0 // 0 // 9998 // 2 // 0 // 0 } 16.1.3 Java内存模型简介 JMM通过各种操作来定义,包括对变量的读写操作,监视器monitor的加锁和释放操作,以及线程的启动和合并操作,JMM为程序中所有的操作定义了一个偏序关系,成为Happens-before,要想保证执行操作B的线程看到A的结果,那么A和B之间必须满足Happens-before关系。如果没有这个关系,JVM可以任意的重排序。 JVM来定义了JMM(Java内存模型)来屏蔽底层平台不同带来的各种同步问题,使得程序员面向JAVA平台预期的结果都是一致的,对于“共享的内存对象的访问保证因果性正是JMM存在的理由”(这句话说的太好了!!!)。 因为没法枚举各种情况,所以提供工具辅助程序员自定义,另外一些就是JMM提供的通用原则,叫做happens-before原则,就是如果动作B要看到动作A的执行结果(无论A/B是否在同一个线程里面执行),那么A/B就需要满足happens-before关系。下面是所有的规则,满足这些规则是一种特殊的处理措施,否则就按照上面背景提到的对于可见性、顺序性是没有保障的,会出现“意外”的情况。 如果多线程写入遍历,没有happens-before来排序,那么会产生race condition。在正确使用同步的的程序中,不存在数据竞争,会表现出串行一致性。 (1)同一个线程中的每个Action都happens-before于出现在其后的任何一个Action。//控制流,而非语句 (2)对一个监视器的解锁happens-before于每一个后续对同一个监视器的加锁。//lock、unlock (3)对volatile字段的写入操作happens-before于每一个后续的同一个字段的读操作。 (4)Thread.start()的调用会happens-before于启动线程里面的动作。 (5)Thread中的所有动作都happens-before于其他线程检查到此线程结束或者Thread.join()中返回或者Thread.isAlive()==false。 (6)一个线程A调用另一个另一个线程B的interrupt()都happens-before于线程A发现B被A中断(B抛出异常或者A检测到B的isInterrupted()或者interrupted())。 (7)一个对象构造函数的结束happens-before与该对象的finalizer的开始 (8)如果A动作happens-before于B动作,而B动作happens-before与C动作,那么A动作happens-before于C动作。 16.1.4 借助同步 piggyback(借助)现有的同步机制可见性。例如在AQS中借助一个volatile的state变量保证happens-before进行排序。 举例:Inner class of FutureTask illustrating synchronization piggybacking. (See JDK source) 还可以记住CountDownLatch,Semaphore,Future,CyclicBarrier等完成自己的希望。 16.2 发布 第三章介绍了如何安全的或者不正确的发布一个对象,其中介绍的各种技术都依赖JMM的保证,而造成发布不正确的原因就是 发布一个共享对象 另外一个线程访问该对象 之间缺少一种happens-before关系。 16.2.1 不安全的发布 缺少happens-before就会发生重排序,会造成发布一个引用的时候,和内部各个field初始化重排序,比如 init field a init field b 发布ref init field c 这时候从使用这角度就会看到一个被部分构造的对象。 错误的延迟初始化将导致不正确的发布,如下代码。这段代码不光有race condition、创建低效等问题还存储在另外一个线程会看到部分构造的Resource实例引用。 @NotThreadSafe public class UnsafeLazyInitialization { private static Resource resource; public static Resource getInstance() { if (resource == null) resource = new Resource(); // unsafe publication return resource; } static class Resource { } } 那么,除非使用final,或者发布操作线程在使用线程开始之前执行,这些都满足了happens-before原则。 16.2.2 安全的发布 使用第三章的各种技术可以安全发布对象,去报发布对象的操作在使用对象的线程开始使用对象的引用之前执行。如果A将X放入BlockingQueue,B从队列中获取X,那么B看到的X与A放入的X相同,实际上由于使用了锁保护,实际B能看到A移交X之前所有的操作。 16.2.3 安全的初始化模式 有时候需要延迟初始化,最简单的方法: @ThreadSafe public class SafeLazyInitialization { private static Resource resource; public synchronized static Resource getInstance() { if (resource == null) resource = new Resource(); return resource; } static class Resource { } } 如果getInstance调用不频繁,这绝对是最佳的。 在初始化中使用static会提供额外的线程安全保证。静态初始化是由JVM在类的初始化阶段执行,并且在类被加载后,在线程使用前的。静态初始化期间,内存写入操作将自动对所有线程可见。因此静态初始化对象不需要显示的同步。下面的代码叫做eager initialization。 @ThreadSafe public class EagerInitialization { private static Resource resource = new Resource(); public static Resource getResource() { return resource; } static class Resource { } } 下面是lazy initialization。JVM推迟ResourceHolder的初始化操作,直到开始使用这个类时才初始化,并且通过一个static来做,不需要额外的同步。 @ThreadSafe public class ResourceFactory { private static class ResourceHolder { public static Resource resource = new Resource(); } public static Resource getResource() { return ResourceFactory.ResourceHolder.resource; } static class Resource { } } 16.2.4 双重检查加锁CDL DCL实际是一种糟糕的方式,是一种anti-pattern,它只在JAVA1.4时代好用,因为早期同步的性能开销较大,但是现在这都不是事了,已经不建议使用。 @NotThreadSafe public class DoubleCheckedLocking { private static Resource resource; public static Resource getInstance() { if (resource == null) { synchronized (DoubleCheckedLocking.class) { if (resource == null) resource = new Resource(); } } return resource; } static class Resource { } } 初始化instance变量的伪代码如下所示: memory = allocate(); //1:分配对象的内存空间 ctorInstance(memory); //2:初始化对象 instance = memory; //3:设置instance指向刚分配的内存地址 之所以会发生上面我说的这种状况,是因为在一些编译器上存在指令排序,初始化过程可能被重排成这样: memory = allocate(); //1:分配对象的内存空间 instance = memory; //3:设置instance指向刚分配的内存地址 //注意,此时对象还没有被初始化! ctorInstance(memory); //2:初始化对象 而volatile存在的意义就在于禁止这种重排!解决办法是声明为volatile类型。这样就可以用DCL了。 @NotThreadSafe public class DoubleCheckedLocking { private static volatile Resource resource; public static Resource getInstance() { if (resource == null) { synchronized (DoubleCheckedLocking.class) { if (resource == null) resource = new Resource(); } } return resource; } static class Resource { } } 16.3 初始化过程中的安全性 final不会被重排序。 下面的states因为是final的所以可以被安全的发布。即使没有volatile,没有锁。但是,如果除了构造函数外其他方法也能修改states。如果类中还有其他非final域,那么其他线程仍然可能看到这些域上不正确的值。也导致了构造过程中的escape。 写final的重排规则: JMM禁止编译器把final域的写重排序到构造函数之外。 编译器会在final域的写之后,构造函数return之前,插入一个StoreStore屏障。这个屏障禁止处理器把final域的写重排序到构造函数之外。也就是说:写final域的重排序规则可以确保:在对象引用为任意线程可见之前,对象的final域已经被正确初始化过了。 读final的重排规则: 在一个线程中,初次读对象引用与初次读该对象包含的final域,JMM禁止处理器重排序这两个操作(注意,这个规则仅仅针对处理器)。编译器会在读final域操作的前面插入一个LoadLoad屏障。也就是说:读final域的重排序规则可以确保:在读一个对象的final域之前,一定会先读包含这个final域的对象的引用。 如果final域是引用类型,那么增加如下约束: 在构造函数内对一个final引用的对象的成员域的写入,与随后在构造函数外把这个被构造对象的引用赋值给一个引用变量,这两个操作之间不能重排序。(个人觉得基本意思也就是确保在构造函数外把这个被构造对象的引用赋值给一个引用变量之前,final域已经完全初始化并且赋值给了当前构造对象的成员域,至于初始化和赋值这两个操作则不确保先后顺序。) @ThreadSafe public class SafeStates { private final Map<String, String> states; public SafeStates() { states = new HashMap<String, String>(); states.put("alaska", "AK"); states.put("alabama", "AL"); /*...*/ states.put("wyoming", "WY"); } public String getAbbreviation(String s) { return states.get(s); } }

优秀的个人博客,低调大师

Java并发编程实战系列6之任务执行(Task Execution)

1. 在线程中执行任务 1.1 串行的执行任务 这是最经典的一个最简单的Socket server的例子,服务器的资源利用率非常低,因为单线程在等待I/O操作完成时,CPU处于空闲状态。从而阻塞了当前请求的延迟,还彻底阻止了其他等待中的请求被处理。 public class SingleThreadWebServer { public static void main(String[] args) throws IOException { ServerSocket socket = new ServerSocket(80); while (true) { Socket connection = socket.accept(); handleRequest(connection); } } private static void handleRequest(Socket connection) { // request-handling logic here } } 1.2 显式地为任务创建线程 任务处理从主线程中分离出来,主循环可以快速等待下一个连接,提高响应性。同时任务可以并行处理了,吞吐量也提高了。 public class ThreadPerTaskWebServer { public static void main(String[] args) throws IOException { ServerSocket socket = new ServerSocket(80); while (true) { final Socket connection = socket.accept(); Runnable task = new Runnable() { public void run() { handleRequest(connection); } }; new Thread(task).start(); } } private static void handleRequest(Socket connection) { // request-handling logic here } } 1.3 无限制创建线程的不足 线程的生命周期开销非常高 资源消耗。大量的空闲线程占用内存,给GC带来压力,同时线程数量过多,竞争CPU资源开销太大。 稳定性。容易引起GC问题,甚至OOM 2 Executor框架 任务就是一组逻辑工作单元(unit of work),而线程则是使任务异步执行的机制。 Executor接口,是代替Thread来做异步执行的入口,接口虽然简单,却为非常灵活强大的异步任务执行框架提供了基础。 提供了一种标准的方法将任务的提交与执行过程解耦,并用Runnable(无返回时)或者Callable(有返回值)表示任务。 Executor基于生产者-消费者模式 提交任务/执行任务分别相当于生产者/消费者,通常是最简单的实现生产者-消费者设计的方式了 2.1 基于Executor改造后的样例如下 将请求处理任务的提交与任务的实际执行解耦,并且只需采用另一种不同的Executor实现,就可以改变服务器的行为,其影响远远小于修改任务提交方式带来的影响 2.2 执行策略 这一节主要介绍做一个Executor框架需要靠那些点? 在什么线程中执行任务? 任务按照什么顺序执行?FIFO/LIFO/优先级 有多少个任务可以并发执行? 队列中允许多少个任务等待? 如果系统过载了要拒绝一个任务,那么选择拒绝哪一个?如何通知客户端任务被拒绝了? 在执行任务过程中能不能有些别的动作before/after或者回调? 各种执行策略都是一种资源管理工具,最佳的策略取决于可用的计算资源以及对服务质量的要求。 因此每当看到 new Thread(runnable).start(); 并且希望有一种灵活的执行策略的时候,请考虑使用Executor来代替 2.3 线程池 在线程池中执行任务比为每个任务分配一个线程优势明显: 重用线程,减少开销。 延迟低,线程是等待任务到达。 最大化挖掘系统资源以及保证稳定性。CPU忙碌但是又不会出现线程竞争资源而耗尽内存或者失败的情况。 Executors可以看做一个工厂,提供如下几种Executor的创建: newCachedThreadPool newFixedThreadPool newSingleThreadExecutor newScheduledThreadPool 2.4 Executor的生命周期 为解决执行服务的生命周期问题,Executor扩展了ExecutorService接口,添加了一些用于生命周期管理的方法 一个优雅停止的例子: 增加生命周期扩展Web服务器的功能 调用stop 客户端请求形式 关闭 2.5 延迟任务与周期任务 使用Timer的弊端在于 如果某个任务执行时间过长,那么将破坏其他TimerTask的定时精确性(执行所有定时任务时只会创建一个线程),只支持基于绝对时间的调度机制,所以对系统时钟变化敏感 TimerTask抛出未检查异常后就会终止定时线程(不会捕获异常) 更加合理的做法是使用ScheduledThreadPoolExecutor,只支持基于相对时间的调度 它是DelayQueue的应用场景 3 找出可利用的并行性 3.1 携带结果的任务Callable和Future Executor框架支持Runnable,同时也支持Callable(它将返回一个值或者抛出一个异常) 在Executor框架中,已提交但是尚未开始的任务可以取消,但是对于那些已经开始执行的任务,只有他们能响应中断时,才能取消。 Future非常实用,他的API如下 内部get的阻塞是靠LockSupport.park来做的,在任务完成后Executor回调finishCompletion方法会依次唤醒被阻塞的线程。 ExecutorService的submit方法接受Runnable和Callable,返回一个Future。ThreadPoolExecutor框架留了一个口子,子类可以重写newTaskFor来决定创建什么Future的实现,默认是FutureTask类。 3.2 示例:使用Future实现页面的渲染器 3.3 CompletionService: Executor与BlockingQueue 计算完成后FutureTask会调用done方法,而CompletionService集成了FutureTask,对于计算完毕的结果直接放在自己维护的BlockingQueue里面,这样上层调用者就可以一个个take或者poll出来。 3.3 示例:使用CompletionService提高渲染性能 void renderPage(CharSequence source) { final List<ImageInfo> info = scanForImageInfo(source); CompletionService<ImageData> completionService = new ExecutorCompletionService<ImageData>(executor); for (final ImageInfo imageInfo : info) completionService.submit(new Callable<ImageData>() { public ImageData call() { return imageInfo.downloadImage(); } }); renderText(source); try { for (int t = 0, n = info.size(); t < n; t++) { Future<ImageData> f = completionService.take(); ImageData imageData = f.get(); renderImage(imageData); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (ExecutionException e) { throw launderThrowable(e.getCause()); } } 6.3.7 为任务设置时限 Future的get支持timeout。 6.3.8 批量提交任务 使用invokeAll方法提交List<Callable>,返回一个List<Future>

优秀的个人博客,低调大师

Python学习笔记:lambda表达式与函数式编程

1,lambda的一般形式是关键字lambda后面跟一个或多个参数,紧跟一个冒号,以后是一个表达式。lambda是一个表达式而不是一个语句。它能够出现在Python语法不允许def出现的地方。作为表达式,lambda返回一个值(即一个新的函数)。lambda用来编写简单的函数,而def用来处理更强大的任务。 [python] view plain copy f=lambdax,y,z:x+y+z printf(1,2,3) g=lambdax,y=2,z=3:x+y+z printg(1,z=4,y=5) 输出结果为: [python] view plain copy 6 10 2,lambda表达式常用来编写跳转表(jump table),就是行为的列表或字典。例如: [python] view plain copy L=[(lambdax:x**2), (lambdax:x**3), (lambdax:x**4)] printL[0](2),L[1](2),L[2](2) D={'f1':(lambda:2+3), 'f2':(lambda:2*3), 'f3':(lambda:2**3)} printD['f1'](),D['f2'](),D['f3']() 输出结果为: [python] view plain copy 4816 568 3,lambda表达式可以嵌套使用,但是从可读性的角度来说,应尽量避免使用嵌套的lambda表达式。 4,map函数可以在序列中映射函数进行操作。例如: [python] view plain copy definc(x): returnx+10 L=[1,2,3,4] printmap(inc,L) printmap((lambdax:x+10),L) 输出结果为: [python] view plain copy [11,12,13,14] [11,12,13,14] 5,列表解析可以实现map函数同样的功能,而且往往比map要快。例如: [python] view plain copy print[x**2forxinrange(10)] printmap((lambdax:x**2),range(10)) 输出结果为: [python] view plain copy [0,1,4,9,16,25,36,49,64,81] [0,1,4,9,16,25,36,49,64,81] 6,列表解析比map更强大。例如: [python] view plain copy print[x+yforxinrange(5)ifx%2==0foryinrange(10)ify%2==1] 输出结果为: [python] view plain copy [1,3,5,7,9,3,5,7,9,11,5,7,9,11,13] 7,生成器函数就像一般的函数,但它们被用作实现迭代协议,因此生成器函数只能在迭代语境中出现。例如: [python] view plain copy defgensquares(N): foriinrange(N): yieldi**2 foriingensquares(5): printi, 输出结果为: [python] view plain copy 014916 8,所有的迭代内容(包括for循环、map调用、列表解析等等)将会自动调用iter函数,来看看是不是支持了迭代协议。 9,生成器表达式就像列表解析一样,但它们是扩在圆括号()中而不是方括号[]中。例如: [python] view plain copy fornumin(x**2forxinrange(5)): printnum, 输出结果为: [python] view plain copy 014916 10,列表解析比for循环具有更好的性能。尽管如此,在编写Python代码时,性能不应该是最优先考虑的。 11,没有return语句时,函数将返回None对象。 12,函数设计的概念: 耦合性:只有在真正必要的情况下才使用全局变量 耦合性:不要改变可变类型的参数,除非调用者希望这样做 耦合性:避免直接改变另一个文件模块中的变量 聚合性:每一个函数都应有一个单一的、统一的目标 13,最后给个默认参数和可变参数的例子: [python] view plain copy defsaver(x=[]): x.append(1) printx saver([2]) saver() saver() saver() 输出结果为: [python] view plain copy [2,1] [1] [1,1] [1,1,1] 原文地址http://www.bieryun.com/748.html

优秀的个人博客,低调大师

Hadoop MapReduce编程 API入门系列之wordcount版本4(八)

是将map、combiner、shuffle、reduce等分开放一个.java里。则需要实现Tool。 代码 1 package zhouls.bigdata.myMapReduce.wordcount2; 2 3 import java.io.IOException; 4 5 import org.apache.commons.lang.StringUtils; 6 import org.apache.hadoop.io.LongWritable; 7 import org.apache.hadoop.io.Text; 8 import org.apache.hadoop.mapreduce.Mapper; 9 10 //4个泛型中,前两个是指定mapper输入数据的类型,KEYIN是输入的key的类型,VALUEIN是输入的value的类型 11 //map 和 reduce 的数据输入输出都是以 key-value对的形式封装的 12 //默认情况下,框架传递给我们的mapper的输入数据中,key是要处理的文本中一行的起始偏移量,这一行的内容作为value 13 public class WCMapper extends Mapper<LongWritable, Text, Text, LongWritable>{ 14 15 //mapreduce框架每读一行数据就调用一次该方法 16 @Override 17 protected void map(LongWritable key, Text value,Context context)throws IOException, InterruptedException{ 18 //具体业务逻辑就写在这个方法体中,而且我们业务要处理的数据已经被框架传递进来,在方法的参数中 key-value 19 //key 是这一行数据的起始偏移量 value 是这一行的文本内容 20 21 //将这一行的内容转换成string类型 22 String line = value.toString(); 23 24 //对这一行的文本按特定分隔符切分 25 //hadoop helloworld 26 String[] words = StringUtils.split(line, " "); 27 28 //遍历这个单词数组输出为kv形式 k:单词 v : 1 29 for(String word : words){//word是k2 30 context.write(new Text(word), new LongWritable(1));//写入word是k2,1是v2 31 // context.write(word,1);等价 32 33 } 34 35 36 } 37 38 39 40 } 1 package zhouls.bigdata.myMapReduce.wordcount2; 2 3 import java.io.IOException; 4 5 import org.apache.hadoop.io.LongWritable; 6 import org.apache.hadoop.io.Text; 7 import org.apache.hadoop.mapreduce.Reducer; 8 9 public class WCReducer extends Reducer<Text, LongWritable, Text, LongWritable>{ 10 11 12 13 //框架在map处理完成之后,将所有kv对缓存起来,进行分组,然后传递一个组<key,valus{}>,调用一次reduce方法 14 //<hello,{1,1,1,1,1,1.....}> 15 @Override 16 protected void reduce(Text key, Iterable<LongWritable> values,Context context)throws IOException, InterruptedException { 17 long count = 0; 18 //遍历value的list,进行累加求和 19 for(LongWritable value:values){//value是v2 20 count += value.get(); 21 } 22 23 //输出这一个单词的统计结果 24 25 context.write(key,new LongWritable(count));//key是k3,count是v3 26 // context.write(key,count); 27 } 28 29 30 31 } 1 package zhouls.bigdata.myMapReduce.wordcount2; 2 3 import org.apache.hadoop.io.LongWritable; 4 import org.apache.hadoop.io.Text; 5 import org.apache.hadoop.mapreduce.Reducer; 6 7 8 /** 9 * combiner必须遵循reducer的规范 10 * 可以把它看成一种在map任务本地运行的reducer 11 * 使用combiner的时候要注意两点 12 * 1、combiner的输入输出数据泛型类型要能跟mapper和reducer匹配 13 * 2、combiner加入之后不能影响最终的业务逻辑运算结果 14 * 15 * 16 */ 17 public class WCCombiner extends Reducer<Text, LongWritable, Text, LongWritable>{ 18 19 } 1 package zhouls.bigdata.myMapReduce.wordcount2; 2 3 import java.io.IOException; 4 5 import org.apache.hadoop.conf.Configuration; 6 import org.apache.hadoop.fs.Path; 7 import org.apache.hadoop.io.LongWritable; 8 import org.apache.hadoop.io.Text; 9 import org.apache.hadoop.mapreduce.Job; 10 import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; 11 import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; 12 13 /** 14 * 用来描述一个特定的作业 15 * 比如,该作业使用哪个类作为逻辑处理中的map,哪个作为reduce 16 * 还可以指定该作业要处理的数据所在的路径 17 * 还可以指定改作业输出的结果放到哪个路径 18 * .... 19 * @author duanhaitao@itcast.cn 20 * 21 */ 22 public class WCRunner { 23 24 public static void main(String[] args) throws Exception { 25 26 Configuration conf = new Configuration(); 27 28 Job wcjob = Job.getInstance(conf); 29 30 //设置整个job所用的那些类在哪个jar包 31 wcjob.setJarByClass(WCRunner.class); 32 33 34 //本job使用的mapper和reducer的类 35 wcjob.setMapperClass(WCMapper.class); 36 wcjob.setReducerClass(WCReducer.class); 37 38 39 //指定本job使用combiner组件,组件所用的类为 40 wcjob.setCombinerClass(WCReducer.class); 41 42 43 //指定reduce的输出数据kv类型 44 wcjob.setOutputKeyClass(Text.class); 45 wcjob.setOutputValueClass(LongWritable.class); 46 47 //指定mapper的输出数据kv类型 48 wcjob.setMapOutputKeyClass(Text.class); 49 wcjob.setMapOutputValueClass(LongWritable.class); 50 51 52 // //指定要处理的输入数据存放路径 53 // FileInputFormat.setInputPaths(wcjob, new Path("hdfs://HadoopMaster:9000/wordcount/wc.txt/")); 54 // 55 // //指定处理结果的输出数据存放路径 56 // FileOutputFormat.setOutputPath(wcjob, new Path("hdfs://HadoopMaster:9000/out/wordcount/wc/")); 57 58 //指定要处理的输入数据存放路径 59 FileInputFormat.setInputPaths(wcjob, new Path("./data/wordcount/wc.txt")); 60 61 //指定处理结果的输出数据存放路径 62 FileOutputFormat.setOutputPath(wcjob, new Path("./out/wordcount/wc/")); 63 64 65 //将job提交给集群运行 66 wcjob.waitForCompletion(true); 67 68 69 } 70 71 72 73 74 } 本文转自大数据躺过的坑博客园博客,原文链接:http://www.cnblogs.com/zlslch/p/6163687.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

Hadoop HDFS编程 API入门系列之HdfsUtil版本2(七)

代码 1 import org.junit.Before; 2 import org.junit.Test; 3 4 package zhouls.bigdata.myWholeHadoop.HDFS.hdfs1; 5 6 import java.io.FileInputStream; 7 import java.io.FileNotFoundException; 8 import java.io.FileOutputStream; 9 import java.io.IOException; 10 import java.net.URI; 11 12 import org.apache.commons.io.IOUtils; 13 import org.apache.hadoop.conf.Configuration; 14 import org.apache.hadoop.fs.FSDataInputStream; 15 import org.apache.hadoop.fs.FSDataOutputStream; 16 import org.apache.hadoop.fs.FileStatus; 17 import org.apache.hadoop.fs.FileSystem; 18 import org.apache.hadoop.fs.LocatedFileStatus; 19 import org.apache.hadoop.fs.Path; 20 import org.apache.hadoop.fs.RemoteIterator; 21 import org.junit.Before; 22 import org.junit.Test; 23 24 public class HdfsUtil { 25 26 FileSystem fs = null; 27 28 29 @Before//@Before是在所拦截单元测试方法执行之前执行一段逻辑,读艾特Before 30 public void init() throws Exception{ 31 32 //读取classpath下的xxx-site.xml 配置文件,并解析其内容,封装到conf对象中 33 Configuration conf = new Configuration(); 34 35 //也可以在代码中对conf中的配置信息进行手动设置,会覆盖掉配置文件中的读取的值 36 conf.set("fs.defaultFS", "hdfs://HadoopMaster:9000/"); 37 38 //根据配置信息,去获取一个具体文件系统的客户端操作实例对象 39 fs = FileSystem.get(new URI("hdfs://HadoopMaster:9000/"),conf,"hadoop"); 40 41 42 } 43 44 45 46 /** 47 * 上传文件,比较底层的写法 48 * 49 * @throws Exception 50 */ 51 @Test//@Test是测试方法提示符,一般与@Before组合使用 52 public void upload() throws Exception { 53 54 Configuration conf = new Configuration(); 55 conf.set("fs.defaultFS", "hdfs://HadoopMaster:9000/"); 56 57 FileSystem fs = FileSystem.get(conf); 58 59 Path dst = new Path("hdfs://HadoopMaster:9000/aa/qingshu.txt"); 60 61 FSDataOutputStream os = fs.create(dst); 62 63 FileInputStream is = new FileInputStream("c:/qingshu.txt"); 64 65 IOUtils.copy(is, os); 66 67 68 } 69 70 /** 71 * 上传文件,封装好的写法 72 * @throws Exception 73 * @throws IOException 74 */ 75 @Test//@Test是测试方法提示符,一般与@Before组合使用 76 public void upload2() throws Exception, IOException{ 77 78 fs.copyFromLocalFile(new Path("c:/qingshu.txt"), new Path("hdfs://HadoopMaster:9000/aaa/bbb/ccc/qingshu2.txt")); 79 80 } 81 82 83 /** 84 * 下载文件 85 * @throws Exception 86 * @throws IllegalArgumentException 87 */ 88 @Test//@Test是测试方法提示符,一般与@Before组合使用 89 public void download() throws Exception { 90 91 fs.copyToLocalFile(new Path("hdfs://HadoopMaster:9000/aa/qingshu2.txt"), new Path("c:/qingshu2.txt")); 92 93 } 94 95 /** 96 * 查看文件信息 97 * @throws IOException 98 * @throws IllegalArgumentException 99 * @throws FileNotFoundException 100 * 101 */ 102 @Test//@Test是测试方法提示符,一般与@Before组合使用 103 public void listFiles() throws FileNotFoundException, IllegalArgumentException, IOException { 104 105 // listFiles列出的是文件信息,而且提供递归遍历 106 RemoteIterator<LocatedFileStatus> files = fs.listFiles(new Path("/"), true); 107 108 while(files.hasNext()){ 109 110 LocatedFileStatus file = files.next(); 111 Path filePath = file.getPath(); 112 String fileName = filePath.getName(); 113 System.out.println(fileName); 114 115 } 116 117 System.out.println("---------------------------------"); 118 119 //listStatus 可以列出文件和文件夹的信息,但是不提供自带的递归遍历 120 FileStatus[] listStatus = fs.listStatus(new Path("/")); 121 for(FileStatus status: listStatus){ 122 123 String name = status.getPath().getName(); 124 System.out.println(name + (status.isDirectory()?" is dir":" is file")); 125 126 } 127 128 } 129 130 /** 131 * 创建文件夹 132 * @throws Exception 133 * @throws IllegalArgumentException 134 */ 135 @Test//@Test是测试方法提示符,一般与@Before组合使用 136 public void mkdir() throws IllegalArgumentException, Exception { 137 138 fs.mkdirs(new Path("/aaa/bbb/ccc")); 139 140 141 } 142 143 /** 144 * 删除文件或文件夹 145 * @throws IOException 146 * @throws IllegalArgumentException 147 */ 148 @Test//@Test是测试方法提示符,一般与@Before组合使用 149 public void rm() throws IllegalArgumentException, IOException { 150 151 fs.delete(new Path("/aa"), true); 152 153 } 154 155 156 public static void main(String[] args) throws Exception { 157 158 Configuration conf = new Configuration(); 159 conf.set("fs.defaultFS", "hdfs://HadoopMaster:9000/"); 160 161 FileSystem fs = FileSystem.get(conf); 162 163 FSDataInputStream is = fs.open(new Path("/jdk-7u65-linux-i586.tar.gz")); 164 165 FileOutputStream os = new FileOutputStream("c:/jdk7.tgz"); 166 167 IOUtils.copy(is, os); 168 } 169 170 171 172 } 1 package zhouls.bigdata.myWholeHadoop.HDFS.hdfs1; 2 3 import java.io.IOException; 4 import java.net.URI; 5 6 7 import org.apache.hadoop.conf.Configuration; 8 import org.apache.hadoop.fs.FileSystem; 9 import org.apache.hadoop.fs.Path; 10 11 public class HdfsUtilHA { 12 public static void main(String[] args) throws Exception{ 13 Configuration conf = new Configuration(); 14 FileSystem fs = FileSystem.get(new URI("hdfs://HadoopMaster/9000"), conf, "hadoop"); 15 fs.copyFromLocalFile(new Path("C:/test.txt"), new Path("hdfs://HadoopMaster/9000")); 16 } 17 } 本文转自大数据躺过的坑博客园博客,原文链接:http://www.cnblogs.com/zlslch/p/6175628.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

Hadoop HDFS编程 API入门系列之RPC版本1(八)

代码 1 package zhouls.bigdata.myWholeHadoop.RPC.rpc1; 2 3 import java.io.IOException; 4 import java.net.InetSocketAddress; 5 6 import org.apache.hadoop.conf.Configuration; 7 import org.apache.hadoop.ipc.RPC; 8 9 public class LoginController { 10 public static void main(String[] args) throws IOException { 11 LoginServiceinterface proxy = RPC.getProxy(LoginServiceinterface.class, 1L, new InetSocketAddress("HadoopMaster", 10000), new Configuration()); 12 String result = proxy.login("angelababy","123456"); 13 System.out.println(result); 14 } 15 } 1 package zhouls.bigdata.myWholeHadoop.RPC.rpc1; 2 3 public interface LoginServiceinterface { 4 public static final long versionID=1L; 5 public String login(String username,String password); 6 } <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="configuration.xsl"?> <!-- Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. See accompanying LICENSE file. --> <!-- Put site-specific property overrides in this file. --> <configuration> <property> <name>fs.default.name</name> <value>hdfs://HadoopMaster:9000</value> <description>The name of the default file system, using 9000 port.</description> </property> <property> <name>hadoop.tmp.dir</name> <value>/tmp</value> <description>A base for other temporary directories.</description> </property> </configuration> <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="configuration.xsl"?> <!-- Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. See accompanying LICENSE file. --> <!-- Put site-specific property overrides in this file. --> <configuration> <property> <name>dfs.namenode.rpc-address</name> <value>HadoopMaster:9000</value> </property> <property> <name>dfs.replication</name> <value>2</value> <description>Set to 1 for pseudo-distributed mode,Set to 2 for distributed mode,Set to 3 for distributed mode.</description> </property> <property> <name>dfs.namenode.http-address</name> <value>HadoopMaster:50070</value> </property> </configuration> 本文转自大数据躺过的坑博客园博客,原文链接:http://www.cnblogs.com/zlslch/p/6175638.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

Hadoop HDFS编程 API入门系列之RPC版本2(九)

代码 1 package zhouls.bigdata.myWholeHadoop.RPC.rpc2; 2 3 public class LoginServiceImpl implements LoginServiceInterface { 4 5 @Override 6 public String login(String username, String password) { 7 8 return username + " logged in successfully!"; 9 } 10 11 } 1 package zhouls.bigdata.myWholeHadoop.RPC.rpc2; 2 3 public class LoginServiceImpl implements LoginServiceInterface { 4 5 @Override 6 public String login(String username, String password) { 7 8 return username + " logged in successfully!"; 9 } 10 11 } 1 package zhouls.bigdata.myWholeHadoop.RPC.rpc2; 2 3 import java.io.IOException; 4 5 import org.apache.hadoop.HadoopIllegalArgumentException; 6 import org.apache.hadoop.conf.Configuration; 7 import org.apache.hadoop.ipc.RPC; 8 import org.apache.hadoop.ipc.RPC.Builder; 9 import org.apache.hadoop.ipc.RPC.Server; 10 11 public class Starter { 12 13 public static void main(String[] args) throws HadoopIllegalArgumentException, IOException { 14 15 16 Builder builder = new RPC.Builder(new Configuration()); 17 18 builder.setBindAddress("HadoopMaster").setPort(10000).setProtocol(LoginServiceInterface.class).setInstance(new LoginServiceImpl()); 19 20 Server server = builder.build(); 21 22 server.start(); 23 24 25 26 } 27 28 29 } 本文转自大数据躺过的坑博客园博客,原文链接:http://www.cnblogs.com/zlslch/p/6175652.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

Hadoop HDFS编程 API入门系列之HdfsUtil版本1(六)

代码 1 package zhouls.bigdata.myWholeHadoop.HDFS.hdfs2; 2 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 6 import org.apache.commons.io.IOUtils; 7 import org.apache.hadoop.conf.Configuration; 8 import org.apache.hadoop.fs.FSDataInputStream; 9 import org.apache.hadoop.fs.FileSystem; 10 import org.apache.hadoop.fs.Path; 11 12 public class HdfsUtil { 13 14 15 public static void main(String[] args) throws IOException { 16 17 // to upload a file to hdfs 18 19 Configuration conf = new Configuration(); 20 21 FileSystem fs = FileSystem.get(conf); 22 23 Path src = new Path("hdfs://HadoopMaster:9000/jdk-7u65-linux-i586.tar.gz"); 24 25 FSDataInputStream in = fs.open(src); 26 27 FileOutputStream os = new FileOutputStream("/home/hadoop/download/jdk.tgz"); 28 29 IOUtils.copy(in, os); 30 } 31 } 本文转自大数据躺过的坑博客园博客,原文链接:http://www.cnblogs.com/zlslch/p/6175616.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

HBase编程 API入门系列之create(管理端而言)(8)

这里,我带领大家,学习更高级的,因为,在开发中,尽量不能去服务器上创建表。 所以,在管理端来创建HBase表。采用线程池的方式(也是生产开发里首推的)。 1 package zhouls.bigdata.HbaseProject.Pool; 2 3 import java.io.IOException; 4 import java.util.concurrent.ExecutorService; 5 import java.util.concurrent.Executors; 6 7 import org.apache.hadoop.conf.Configuration; 8 import org.apache.hadoop.hbase.HBaseConfiguration; 9 import org.apache.hadoop.hbase.client.HConnection; 10 import org.apache.hadoop.hbase.client.HConnectionManager; 11 12 13 public class TableConnection { 14 private TableConnection(){ 15 } 16 17 private static HConnection connection = null; 18 19 public static HConnection getConnection(){ 20 if(connection == null){ 21 ExecutorService pool = Executors.newFixedThreadPool(10);//建立一个固定大小的线程池 22 Configuration conf = HBaseConfiguration.create(); 23 conf.set("hbase.zookeeper.quorum","HadoopMaster:2181,HadoopSlave1:2181,HadoopSlave2:2181"); 24 try{ 25 connection = HConnectionManager.createConnection(conf,pool);//创建连接时,拿到配置文件和线程池 26 }catch (IOException e){ 27 } 28 } 29 return connection; 30 } 31 } 1、最简单的创建HBase表 查看,当前已创建有的表 hbase(main):055:0>list TABLE test_table test_table2 2 row(s) in 1.1030 seconds => ["test_table", "test_table2"] hbase(main):056:0> 1 package zhouls.bigdata.HbaseProject.Pool; 2 3 import java.io.IOException; 4 5 import zhouls.bigdata.HbaseProject.Pool.TableConnection; 6 7 import javax.xml.transform.Result; 8 9 import org.apache.hadoop.conf.Configuration; 10 import org.apache.hadoop.hbase.Cell; 11 import org.apache.hadoop.hbase.CellUtil; 12 import org.apache.hadoop.hbase.HBaseConfiguration; 13 import org.apache.hadoop.hbase.HColumnDescriptor; 14 import org.apache.hadoop.hbase.HTableDescriptor; 15 import org.apache.hadoop.hbase.MasterNotRunningException; 16 import org.apache.hadoop.hbase.TableName; 17 import org.apache.hadoop.hbase.ZooKeeperConnectionException; 18 import org.apache.hadoop.hbase.client.Delete; 19 import org.apache.hadoop.hbase.client.Get; 20 import org.apache.hadoop.hbase.client.HBaseAdmin; 21 import org.apache.hadoop.hbase.client.HTable; 22 import org.apache.hadoop.hbase.client.HTableInterface; 23 import org.apache.hadoop.hbase.client.Put; 24 import org.apache.hadoop.hbase.client.ResultScanner; 25 import org.apache.hadoop.hbase.client.Scan; 26 import org.apache.hadoop.hbase.util.Bytes; 27 28 public class HBaseTest { 29 public static void main(String[] args) throws Exception { 30 // HTable table = new HTable(getConfig(),TableName.valueOf("test_table"));//表名是test_table 31 // Put put = new Put(Bytes.toBytes("row_04"));//行键是row_04 32 // put.add(Bytes.toBytes("f"),Bytes.toBytes("name"),Bytes.toBytes("Andy1"));//列簇是f,列修饰符是name,值是Andy0 33 // put.add(Bytes.toBytes("f2"),Bytes.toBytes("name"),Bytes.toBytes("Andy3"));//列簇是f2,列修饰符是name,值是Andy3 34 // table.put(put); 35 // table.close(); 36 37 // Get get = new Get(Bytes.toBytes("row_04")); 38 // get.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("age"));如现在这样,不指定,默认把所有的全拿出来 39 // org.apache.hadoop.hbase.client.Result rest = table.get(get); 40 // System.out.println(rest.toString()); 41 // table.close(); 42 43 // Delete delete = new Delete(Bytes.toBytes("row_2")); 44 // delete.deleteColumn(Bytes.toBytes("f1"), Bytes.toBytes("email")); 45 // delete.deleteColumn(Bytes.toBytes("f1"), Bytes.toBytes("name")); 46 // table.delete(delete); 47 // table.close(); 48 49 // Delete delete = new Delete(Bytes.toBytes("row_04")); 50 //// delete.deleteColumn(Bytes.toBytes("f"), Bytes.toBytes("name"));//deleteColumn是删除某一个列簇里的最新时间戳版本。 51 // delete.deleteColumns(Bytes.toBytes("f"), Bytes.toBytes("name"));//delete.deleteColumns是删除某个列簇里的所有时间戳版本。 52 // table.delete(delete); 53 // table.close(); 54 55 56 // Scan scan = new Scan(); 57 // scan.setStartRow(Bytes.toBytes("row_01"));//包含开始行键 58 // scan.setStopRow(Bytes.toBytes("row_03"));//不包含结束行键 59 // scan.addColumn(Bytes.toBytes("f"), Bytes.toBytes("name")); 60 // ResultScanner rst = table.getScanner(scan);//整个循环 61 // System.out.println(rst.toString()); 62 // for (org.apache.hadoop.hbase.client.Result next = rst.next();next !=null;next = rst.next() ){ 63 // for(Cell cell:next.rawCells()){//某个row key下的循坏 64 // System.out.println(next.toString()); 65 // System.out.println("family:" + Bytes.toString(CellUtil.cloneFamily(cell))); 66 // System.out.println("col:" + Bytes.toString(CellUtil.cloneQualifier(cell))); 67 // System.out.println("value" + Bytes.toString(CellUtil.cloneValue(cell))); 68 // } 69 // } 70 // table.close(); 71 72 HBaseTest hbasetest =new HBaseTest(); 73 // hbasetest.insertValue(); 74 // hbasetest.getValue(); 75 // hbasetest.delete(); 76 // hbasetest.scanValue(); 77 hbasetest.createTable("test_table3", "f"); 78 } 79 80 81 //生产开发中,建议这样用线程池做 82 // public void insertValue() throws Exception{ 83 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 84 // Put put = new Put(Bytes.toBytes("row_01"));//行键是row_01 85 // put.add(Bytes.toBytes("f"),Bytes.toBytes("name"),Bytes.toBytes("Andy0")); 86 // table.put(put); 87 // table.close(); 88 // } 89 90 91 92 //生产开发中,建议这样用线程池做 93 // public void getValue() throws Exception{ 94 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 95 // Get get = new Get(Bytes.toBytes("row_03")); 96 // get.addColumn(Bytes.toBytes("f"), Bytes.toBytes("name")); 97 // org.apache.hadoop.hbase.client.Result rest = table.get(get); 98 // System.out.println(rest.toString()); 99 // table.close(); 100 // } 101 // 102 //生产开发中,建议这样用线程池做 103 // public void delete() throws Exception{ 104 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 105 // Delete delete = new Delete(Bytes.toBytes("row_01")); 106 // delete.deleteColumn(Bytes.toBytes("f"), Bytes.toBytes("name"));//deleteColumn是删除某一个列簇里的最新时间戳版本。 107 //// delete.deleteColumns(Bytes.toBytes("f"), Bytes.toBytes("name"));//delete.deleteColumns是删除某个列簇里的所有时间戳版本。 108 // table.delete(delete); 109 // table.close(); 110 // } 111 //生产开发中,建议这样用线程池做 112 // public void scanValue() throws Exception{ 113 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 114 // Scan scan = new Scan(); 115 // scan.setStartRow(Bytes.toBytes("row_02"));//包含开始行键 116 // scan.setStopRow(Bytes.toBytes("row_04"));//不包含结束行键 117 // scan.addColumn(Bytes.toBytes("f"), Bytes.toBytes("name")); 118 // ResultScanner rst = table.getScanner(scan);//整个循环 119 // System.out.println(rst.toString()); 120 // for (org.apache.hadoop.hbase.client.Result next = rst.next();next !=null;next = rst.next() ){ 121 // for(Cell cell:next.rawCells()){//某个row key下的循坏 122 // System.out.println(next.toString()); 123 // System.out.println("family:" + Bytes.toString(CellUtil.cloneFamily(cell))); 124 // System.out.println("col:" + Bytes.toString(CellUtil.cloneQualifier(cell))); 125 // System.out.println("value" + Bytes.toString(CellUtil.cloneValue(cell))); 126 // } 127 // } 128 // table.close(); 129 // } 130 // 131 132 //生产开发中,建议这样用线程池做 133 public void createTable(String tableName,String family) throws MasterNotRunningException, ZooKeeperConnectionException, IOException{ 134 Configuration conf = HBaseConfiguration.create(getConfig()); 135 HBaseAdmin admin = new HBaseAdmin(conf); 136 HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(tableName)); 137 HColumnDescriptor hcd = new HColumnDescriptor(family); 138 tableDesc.addFamily(hcd); 139 admin.createTable(tableDesc); 140 admin.close(); 141 } 142 143 144 145 public static Configuration getConfig(){ 146 Configuration configuration = new Configuration(); 147 // conf.set("hbase.rootdir","hdfs:HadoopMaster:9000/hbase"); 148 configuration.set("hbase.zookeeper.quorum", "HadoopMaster:2181,HadoopSlave1:2181,HadoopSlave2:2181"); 149 return configuration; 150 } 151 } 即,创建成功。 hbase(main):057:0>list TABLE test_table test_table2 2 row(s) in 4.1700 seconds => ["test_table", "test_table2"] hbase(main):058:0>list TABLE test_table test_table2 test_table3 3 row(s) in 0.0560 seconds => ["test_table", "test_table2", "test_table3"] hbase(main):059:0> desc 'test_table3' Table test_table3 is ENABLED test_table3 COLUMN FAMILIES DESCRIPTION {NAME => 'f', DATA_BLOCK_ENCODING => 'NONE', BLOOMFILTER => 'ROW', REPLICATION_SCOPE => '0', VERSIONS => '1', COMPRESSION => 'NONE', MIN_VERSIONS => '0', TTL => 'FOREVER', KEEP_DELETED_CELLS => 'FALSE', BLOCKSIZE => '65536', IN_MEMORY => 'false', BLOCKCACHE => 'true'} 1 row(s) in 1.2370 seconds 2、带最大版本数,创建HBase表 1 package zhouls.bigdata.HbaseProject.Pool; 2 3 import java.io.IOException; 4 5 import zhouls.bigdata.HbaseProject.Pool.TableConnection; 6 7 import javax.xml.transform.Result; 8 9 import org.apache.hadoop.conf.Configuration; 10 import org.apache.hadoop.hbase.Cell; 11 import org.apache.hadoop.hbase.CellUtil; 12 import org.apache.hadoop.hbase.HBaseConfiguration; 13 import org.apache.hadoop.hbase.HColumnDescriptor; 14 import org.apache.hadoop.hbase.HTableDescriptor; 15 import org.apache.hadoop.hbase.MasterNotRunningException; 16 import org.apache.hadoop.hbase.TableName; 17 import org.apache.hadoop.hbase.ZooKeeperConnectionException; 18 import org.apache.hadoop.hbase.client.Delete; 19 import org.apache.hadoop.hbase.client.Get; 20 import org.apache.hadoop.hbase.client.HBaseAdmin; 21 import org.apache.hadoop.hbase.client.HTable; 22 import org.apache.hadoop.hbase.client.HTableInterface; 23 import org.apache.hadoop.hbase.client.Put; 24 import org.apache.hadoop.hbase.client.ResultScanner; 25 import org.apache.hadoop.hbase.client.Scan; 26 import org.apache.hadoop.hbase.util.Bytes; 27 28 public class HBaseTest { 29 public static void main(String[] args) throws Exception { 30 // HTable table = new HTable(getConfig(),TableName.valueOf("test_table"));//表名是test_table 31 // Put put = new Put(Bytes.toBytes("row_04"));//行键是row_04 32 // put.add(Bytes.toBytes("f"),Bytes.toBytes("name"),Bytes.toBytes("Andy1"));//列簇是f,列修饰符是name,值是Andy0 33 // put.add(Bytes.toBytes("f2"),Bytes.toBytes("name"),Bytes.toBytes("Andy3"));//列簇是f2,列修饰符是name,值是Andy3 34 // table.put(put); 35 // table.close(); 36 37 // Get get = new Get(Bytes.toBytes("row_04")); 38 // get.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("age"));如现在这样,不指定,默认把所有的全拿出来 39 // org.apache.hadoop.hbase.client.Result rest = table.get(get); 40 // System.out.println(rest.toString()); 41 // table.close(); 42 43 // Delete delete = new Delete(Bytes.toBytes("row_2")); 44 // delete.deleteColumn(Bytes.toBytes("f1"), Bytes.toBytes("email")); 45 // delete.deleteColumn(Bytes.toBytes("f1"), Bytes.toBytes("name")); 46 // table.delete(delete); 47 // table.close(); 48 49 // Delete delete = new Delete(Bytes.toBytes("row_04")); 50 //// delete.deleteColumn(Bytes.toBytes("f"), Bytes.toBytes("name"));//deleteColumn是删除某一个列簇里的最新时间戳版本。 51 // delete.deleteColumns(Bytes.toBytes("f"), Bytes.toBytes("name"));//delete.deleteColumns是删除某个列簇里的所有时间戳版本。 52 // table.delete(delete); 53 // table.close(); 54 55 56 // Scan scan = new Scan(); 57 // scan.setStartRow(Bytes.toBytes("row_01"));//包含开始行键 58 // scan.setStopRow(Bytes.toBytes("row_03"));//不包含结束行键 59 // scan.addColumn(Bytes.toBytes("f"), Bytes.toBytes("name")); 60 // ResultScanner rst = table.getScanner(scan);//整个循环 61 // System.out.println(rst.toString()); 62 // for (org.apache.hadoop.hbase.client.Result next = rst.next();next !=null;next = rst.next() ){ 63 // for(Cell cell:next.rawCells()){//某个row key下的循坏 64 // System.out.println(next.toString()); 65 // System.out.println("family:" + Bytes.toString(CellUtil.cloneFamily(cell))); 66 // System.out.println("col:" + Bytes.toString(CellUtil.cloneQualifier(cell))); 67 // System.out.println("value" + Bytes.toString(CellUtil.cloneValue(cell))); 68 // } 69 // } 70 // table.close(); 71 72 HBaseTest hbasetest =new HBaseTest(); 73 // hbasetest.insertValue(); 74 // hbasetest.getValue(); 75 // hbasetest.delete(); 76 // hbasetest.scanValue(); 77 hbasetest.createTable("test_table4", "f"); 78 } 79 80 81 //生产开发中,建议这样用线程池做 82 // public void insertValue() throws Exception{ 83 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 84 // Put put = new Put(Bytes.toBytes("row_01"));//行键是row_01 85 // put.add(Bytes.toBytes("f"),Bytes.toBytes("name"),Bytes.toBytes("Andy0")); 86 // table.put(put); 87 // table.close(); 88 // } 89 90 91 92 //生产开发中,建议这样用线程池做 93 // public void getValue() throws Exception{ 94 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 95 // Get get = new Get(Bytes.toBytes("row_03")); 96 // get.addColumn(Bytes.toBytes("f"), Bytes.toBytes("name")); 97 // org.apache.hadoop.hbase.client.Result rest = table.get(get); 98 // System.out.println(rest.toString()); 99 // table.close(); 100 // } 101 // 102 //生产开发中,建议这样用线程池做 103 // public void delete() throws Exception{ 104 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 105 // Delete delete = new Delete(Bytes.toBytes("row_01")); 106 // delete.deleteColumn(Bytes.toBytes("f"), Bytes.toBytes("name"));//deleteColumn是删除某一个列簇里的最新时间戳版本。 107 //// delete.deleteColumns(Bytes.toBytes("f"), Bytes.toBytes("name"));//delete.deleteColumns是删除某个列簇里的所有时间戳版本。 108 // table.delete(delete); 109 // table.close(); 110 // } 111 112 113 //生产开发中,建议这样用线程池做 114 // public void scanValue() throws Exception{ 115 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 116 // Scan scan = new Scan(); 117 // scan.setStartRow(Bytes.toBytes("row_02"));//包含开始行键 118 // scan.setStopRow(Bytes.toBytes("row_04"));//不包含结束行键 119 // scan.addColumn(Bytes.toBytes("f"), Bytes.toBytes("name")); 120 // ResultScanner rst = table.getScanner(scan);//整个循环 121 // System.out.println(rst.toString()); 122 // for (org.apache.hadoop.hbase.client.Result next = rst.next();next !=null;next = rst.next() ){ 123 // for(Cell cell:next.rawCells()){//某个row key下的循坏 124 // System.out.println(next.toString()); 125 // System.out.println("family:" + Bytes.toString(CellUtil.cloneFamily(cell))); 126 // System.out.println("col:" + Bytes.toString(CellUtil.cloneQualifier(cell))); 127 // System.out.println("value" + Bytes.toString(CellUtil.cloneValue(cell))); 128 // } 129 // } 130 // table.close(); 131 // } 132 // 133 134 //生产开发中,建议这样用线程池做 135 public void createTable(String tableName,String family) throws MasterNotRunningException, ZooKeeperConnectionException, IOException{ 136 Configuration conf = HBaseConfiguration.create(getConfig()); 137 HBaseAdmin admin = new HBaseAdmin(conf); 138 HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(tableName)); 139 HColumnDescriptor hcd = new HColumnDescriptor(family); 140 hcd.setMaxVersions(3); 141 tableDesc.addFamily(hcd); 142 admin.createTable(tableDesc); 143 admin.close(); 144 } 145 146 147 148 public static Configuration getConfig(){ 149 Configuration configuration = new Configuration(); 150 // conf.set("hbase.rootdir","hdfs:HadoopMaster:9000/hbase"); 151 configuration.set("hbase.zookeeper.quorum", "HadoopMaster:2181,HadoopSlave1:2181,HadoopSlave2:2181"); 152 return configuration; 153 } 154 } hbase(main):060:0>list TABLE test_table test_table2 test_table3 test_table4 4 row(s) in 0.0980 seconds => ["test_table", "test_table2", "test_table3", "test_table4"] hbase(main):061:0>desc 'test_table4' Table test_table4 is ENABLED test_table4 COLUMN FAMILIES DESCRIPTION {NAME => 'f', DATA_BLOCK_ENCODING => 'NONE', BLOOMFILTER => 'ROW', REPLICATION_SCOPE => '0', VERSIONS => '3', COMPRESSION => 'NONE', MIN_VERSIONS => '0', TTL => 'FOREVER', KEEP_DELETED_CELLS => 'FALSE', BLOCKSIZE => '65536', IN_MEMORY => 'false', BLOCKCACHE => 'true'} 1 row(s) in 0.1480 seconds hbase(main):062:0> 3、更多带的创建操作,创建HBase表 1 package zhouls.bigdata.HbaseProject.Pool; 2 3 import java.io.IOException; 4 5 import zhouls.bigdata.HbaseProject.Pool.TableConnection; 6 7 import javax.xml.transform.Result; 8 9 import org.apache.hadoop.conf.Configuration; 10 import org.apache.hadoop.hbase.Cell; 11 import org.apache.hadoop.hbase.CellUtil; 12 import org.apache.hadoop.hbase.HBaseConfiguration; 13 import org.apache.hadoop.hbase.HColumnDescriptor; 14 import org.apache.hadoop.hbase.HTableDescriptor; 15 import org.apache.hadoop.hbase.MasterNotRunningException; 16 import org.apache.hadoop.hbase.TableName; 17 import org.apache.hadoop.hbase.ZooKeeperConnectionException; 18 import org.apache.hadoop.hbase.client.Delete; 19 import org.apache.hadoop.hbase.client.Get; 20 import org.apache.hadoop.hbase.client.HBaseAdmin; 21 import org.apache.hadoop.hbase.client.HTable; 22 import org.apache.hadoop.hbase.client.HTableInterface; 23 import org.apache.hadoop.hbase.client.Put; 24 import org.apache.hadoop.hbase.client.ResultScanner; 25 import org.apache.hadoop.hbase.client.Scan; 26 import org.apache.hadoop.hbase.util.Bytes; 27 28 public class HBaseTest { 29 public static void main(String[] args) throws Exception { 30 // HTable table = new HTable(getConfig(),TableName.valueOf("test_table"));//表名是test_table 31 // Put put = new Put(Bytes.toBytes("row_04"));//行键是row_04 32 // put.add(Bytes.toBytes("f"),Bytes.toBytes("name"),Bytes.toBytes("Andy1"));//列簇是f,列修饰符是name,值是Andy0 33 // put.add(Bytes.toBytes("f2"),Bytes.toBytes("name"),Bytes.toBytes("Andy3"));//列簇是f2,列修饰符是name,值是Andy3 34 // table.put(put); 35 // table.close(); 36 37 // Get get = new Get(Bytes.toBytes("row_04")); 38 // get.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("age"));如现在这样,不指定,默认把所有的全拿出来 39 // org.apache.hadoop.hbase.client.Result rest = table.get(get); 40 // System.out.println(rest.toString()); 41 // table.close(); 42 43 // Delete delete = new Delete(Bytes.toBytes("row_2")); 44 // delete.deleteColumn(Bytes.toBytes("f1"), Bytes.toBytes("email")); 45 // delete.deleteColumn(Bytes.toBytes("f1"), Bytes.toBytes("name")); 46 // table.delete(delete); 47 // table.close(); 48 49 // Delete delete = new Delete(Bytes.toBytes("row_04")); 50 //// delete.deleteColumn(Bytes.toBytes("f"), Bytes.toBytes("name"));//deleteColumn是删除某一个列簇里的最新时间戳版本。 51 // delete.deleteColumns(Bytes.toBytes("f"), Bytes.toBytes("name"));//delete.deleteColumns是删除某个列簇里的所有时间戳版本。 52 // table.delete(delete); 53 // table.close(); 54 55 56 // Scan scan = new Scan(); 57 // scan.setStartRow(Bytes.toBytes("row_01"));//包含开始行键 58 // scan.setStopRow(Bytes.toBytes("row_03"));//不包含结束行键 59 // scan.addColumn(Bytes.toBytes("f"), Bytes.toBytes("name")); 60 // ResultScanner rst = table.getScanner(scan);//整个循环 61 // System.out.println(rst.toString()); 62 // for (org.apache.hadoop.hbase.client.Result next = rst.next();next !=null;next = rst.next() ){ 63 // for(Cell cell:next.rawCells()){//某个row key下的循坏 64 // System.out.println(next.toString()); 65 // System.out.println("family:" + Bytes.toString(CellUtil.cloneFamily(cell))); 66 // System.out.println("col:" + Bytes.toString(CellUtil.cloneQualifier(cell))); 67 // System.out.println("value" + Bytes.toString(CellUtil.cloneValue(cell))); 68 // } 69 // } 70 // table.close(); 71 72 HBaseTest hbasetest =new HBaseTest(); 73 // hbasetest.insertValue(); 74 // hbasetest.getValue(); 75 // hbasetest.delete(); 76 // hbasetest.scanValue(); 77 hbasetest.createTable("test_table4", "f"); 78 } 79 80 81 //生产开发中,建议这样用线程池做 82 // public void insertValue() throws Exception{ 83 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 84 // Put put = new Put(Bytes.toBytes("row_01"));//行键是row_01 85 // put.add(Bytes.toBytes("f"),Bytes.toBytes("name"),Bytes.toBytes("Andy0")); 86 // table.put(put); 87 // table.close(); 88 // } 89 90 91 92 //生产开发中,建议这样用线程池做 93 // public void getValue() throws Exception{ 94 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 95 // Get get = new Get(Bytes.toBytes("row_03")); 96 // get.addColumn(Bytes.toBytes("f"), Bytes.toBytes("name")); 97 // org.apache.hadoop.hbase.client.Result rest = table.get(get); 98 // System.out.println(rest.toString()); 99 // table.close(); 100 // } 101 // 102 //生产开发中,建议这样用线程池做 103 // public void delete() throws Exception{ 104 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 105 // Delete delete = new Delete(Bytes.toBytes("row_01")); 106 // delete.deleteColumn(Bytes.toBytes("f"), Bytes.toBytes("name"));//deleteColumn是删除某一个列簇里的最新时间戳版本。 107 //// delete.deleteColumns(Bytes.toBytes("f"), Bytes.toBytes("name"));//delete.deleteColumns是删除某个列簇里的所有时间戳版本。 108 // table.delete(delete); 109 // table.close(); 110 // } 111 112 113 //生产开发中,建议这样用线程池做 114 // public void scanValue() throws Exception{ 115 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 116 // Scan scan = new Scan(); 117 // scan.setStartRow(Bytes.toBytes("row_02"));//包含开始行键 118 // scan.setStopRow(Bytes.toBytes("row_04"));//不包含结束行键 119 // scan.addColumn(Bytes.toBytes("f"), Bytes.toBytes("name")); 120 // ResultScanner rst = table.getScanner(scan);//整个循环 121 // System.out.println(rst.toString()); 122 // for (org.apache.hadoop.hbase.client.Result next = rst.next();next !=null;next = rst.next() ){ 123 // for(Cell cell:next.rawCells()){//某个row key下的循坏 124 // System.out.println(next.toString()); 125 // System.out.println("family:" + Bytes.toString(CellUtil.cloneFamily(cell))); 126 // System.out.println("col:" + Bytes.toString(CellUtil.cloneQualifier(cell))); 127 // System.out.println("value" + Bytes.toString(CellUtil.cloneValue(cell))); 128 // } 129 // } 130 // table.close(); 131 // } 132 // 133 134 //生产开发中,建议这样用线程池做 135 public void createTable(String tableName,String family) throws MasterNotRunningException, ZooKeeperConnectionException, IOException{ 136 Configuration conf = HBaseConfiguration.create(getConfig()); 137 HBaseAdmin admin = new HBaseAdmin(conf); 138 HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(tableName)); 139 HColumnDescriptor hcd = new HColumnDescriptor(family); 140 hcd.setMaxVersions(3); 141 // hcd.set//很多的带创建操作,我这里只抛砖引玉的作用 142 tableDesc.addFamily(hcd); 143 admin.createTable(tableDesc); 144 admin.close(); 145 } 146 147 148 149 public static Configuration getConfig(){ 150 Configuration configuration = new Configuration(); 151 // conf.set("hbase.rootdir","hdfs:HadoopMaster:9000/hbase"); 152 configuration.set("hbase.zookeeper.quorum", "HadoopMaster:2181,HadoopSlave1:2181,HadoopSlave2:2181"); 153 return configuration; 154 } 155 } 4、先判断表是否存在,再来删创建HBase表(生产开发首推) 1 package zhouls.bigdata.HbaseProject.Pool; 2 3 import java.io.IOException; 4 5 import zhouls.bigdata.HbaseProject.Pool.TableConnection; 6 7 import javax.xml.transform.Result; 8 9 import org.apache.hadoop.conf.Configuration; 10 import org.apache.hadoop.hbase.Cell; 11 import org.apache.hadoop.hbase.CellUtil; 12 import org.apache.hadoop.hbase.HBaseConfiguration; 13 import org.apache.hadoop.hbase.HColumnDescriptor; 14 import org.apache.hadoop.hbase.HTableDescriptor; 15 import org.apache.hadoop.hbase.MasterNotRunningException; 16 import org.apache.hadoop.hbase.TableName; 17 import org.apache.hadoop.hbase.ZooKeeperConnectionException; 18 import org.apache.hadoop.hbase.client.Delete; 19 import org.apache.hadoop.hbase.client.Get; 20 import org.apache.hadoop.hbase.client.HBaseAdmin; 21 import org.apache.hadoop.hbase.client.HTable; 22 import org.apache.hadoop.hbase.client.HTableInterface; 23 import org.apache.hadoop.hbase.client.Put; 24 import org.apache.hadoop.hbase.client.ResultScanner; 25 import org.apache.hadoop.hbase.client.Scan; 26 import org.apache.hadoop.hbase.util.Bytes; 27 28 public class HBaseTest { 29 public static void main(String[] args) throws Exception { 30 // HTable table = new HTable(getConfig(),TableName.valueOf("test_table"));//表名是test_table 31 // Put put = new Put(Bytes.toBytes("row_04"));//行键是row_04 32 // put.add(Bytes.toBytes("f"),Bytes.toBytes("name"),Bytes.toBytes("Andy1"));//列簇是f,列修饰符是name,值是Andy0 33 // put.add(Bytes.toBytes("f2"),Bytes.toBytes("name"),Bytes.toBytes("Andy3"));//列簇是f2,列修饰符是name,值是Andy3 34 // table.put(put); 35 // table.close(); 36 37 // Get get = new Get(Bytes.toBytes("row_04")); 38 // get.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("age"));如现在这样,不指定,默认把所有的全拿出来 39 // org.apache.hadoop.hbase.client.Result rest = table.get(get); 40 // System.out.println(rest.toString()); 41 // table.close(); 42 43 // Delete delete = new Delete(Bytes.toBytes("row_2")); 44 // delete.deleteColumn(Bytes.toBytes("f1"), Bytes.toBytes("email")); 45 // delete.deleteColumn(Bytes.toBytes("f1"), Bytes.toBytes("name")); 46 // table.delete(delete); 47 // table.close(); 48 49 // Delete delete = new Delete(Bytes.toBytes("row_04")); 50 //// delete.deleteColumn(Bytes.toBytes("f"), Bytes.toBytes("name"));//deleteColumn是删除某一个列簇里的最新时间戳版本。 51 // delete.deleteColumns(Bytes.toBytes("f"), Bytes.toBytes("name"));//delete.deleteColumns是删除某个列簇里的所有时间戳版本。 52 // table.delete(delete); 53 // table.close(); 54 55 56 // Scan scan = new Scan(); 57 // scan.setStartRow(Bytes.toBytes("row_01"));//包含开始行键 58 // scan.setStopRow(Bytes.toBytes("row_03"));//不包含结束行键 59 // scan.addColumn(Bytes.toBytes("f"), Bytes.toBytes("name")); 60 // ResultScanner rst = table.getScanner(scan);//整个循环 61 // System.out.println(rst.toString()); 62 // for (org.apache.hadoop.hbase.client.Result next = rst.next();next !=null;next = rst.next() ){ 63 // for(Cell cell:next.rawCells()){//某个row key下的循坏 64 // System.out.println(next.toString()); 65 // System.out.println("family:" + Bytes.toString(CellUtil.cloneFamily(cell))); 66 // System.out.println("col:" + Bytes.toString(CellUtil.cloneQualifier(cell))); 67 // System.out.println("value" + Bytes.toString(CellUtil.cloneValue(cell))); 68 // } 69 // } 70 // table.close(); 71 72 HBaseTest hbasetest =new HBaseTest(); 73 // hbasetest.insertValue(); 74 // hbasetest.getValue(); 75 // hbasetest.delete(); 76 // hbasetest.scanValue(); 77 hbasetest.createTable("test_table3", "f");//先判断表是否存在,再来创建HBase表(生产开发首推) 78 // hbasetest.deleteTable("test_table4");//先判断表是否存在,再来删除HBase表(生产开发首推) 79 } 80 81 82 //生产开发中,建议这样用线程池做 83 // public void insertValue() throws Exception{ 84 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 85 // Put put = new Put(Bytes.toBytes("row_01"));//行键是row_01 86 // put.add(Bytes.toBytes("f"),Bytes.toBytes("name"),Bytes.toBytes("Andy0")); 87 // table.put(put); 88 // table.close(); 89 // } 90 91 92 93 //生产开发中,建议这样用线程池做 94 // public void getValue() throws Exception{ 95 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 96 // Get get = new Get(Bytes.toBytes("row_03")); 97 // get.addColumn(Bytes.toBytes("f"), Bytes.toBytes("name")); 98 // org.apache.hadoop.hbase.client.Result rest = table.get(get); 99 // System.out.println(rest.toString()); 100 // table.close(); 101 // } 102 103 104 //生产开发中,建议这样用线程池做 105 // public void delete() throws Exception{ 106 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 107 // Delete delete = new Delete(Bytes.toBytes("row_01")); 108 // delete.deleteColumn(Bytes.toBytes("f"), Bytes.toBytes("name"));//deleteColumn是删除某一个列簇里的最新时间戳版本。 109 //// delete.deleteColumns(Bytes.toBytes("f"), Bytes.toBytes("name"));//delete.deleteColumns是删除某个列簇里的所有时间戳版本。 110 // table.delete(delete); 111 // table.close(); 112 // } 113 114 115 //生产开发中,建议这样用线程池做 116 // public void scanValue() throws Exception{ 117 // HTableInterface table = TableConnection.getConnection().getTable(TableName.valueOf("test_table")); 118 // Scan scan = new Scan(); 119 // scan.setStartRow(Bytes.toBytes("row_02"));//包含开始行键 120 // scan.setStopRow(Bytes.toBytes("row_04"));//不包含结束行键 121 // scan.addColumn(Bytes.toBytes("f"), Bytes.toBytes("name")); 122 // ResultScanner rst = table.getScanner(scan);//整个循环 123 // System.out.println(rst.toString()); 124 // for (org.apache.hadoop.hbase.client.Result next = rst.next();next !=null;next = rst.next() ){ 125 // for(Cell cell:next.rawCells()){//某个row key下的循坏 126 // System.out.println(next.toString()); 127 // System.out.println("family:" + Bytes.toString(CellUtil.cloneFamily(cell))); 128 // System.out.println("col:" + Bytes.toString(CellUtil.cloneQualifier(cell))); 129 // System.out.println("value" + Bytes.toString(CellUtil.cloneValue(cell))); 130 // } 131 // } 132 // table.close(); 133 // } 134 135 136 //生产开发中,建议这样用线程池做 137 public void createTable(String tableName,String family) throws MasterNotRunningException, ZooKeeperConnectionException, IOException{ 138 Configuration conf = HBaseConfiguration.create(getConfig()); 139 HBaseAdmin admin = new HBaseAdmin(conf); 140 HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(tableName)); 141 HColumnDescriptor hcd = new HColumnDescriptor(family); 142 hcd.setMaxVersions(3); 143 // hcd.set//很多的带创建操作,我这里只抛砖引玉的作用 144 tableDesc.addFamily(hcd); 145 if (!admin.tableExists(tableName)){ 146 admin.createTable(tableDesc); 147 }else{ 148 System.out.println(tableName + "exist"); 149 } 150 admin.close(); 151 } 152 153 154 //生产开发中,建议这样用线程池做 155 // public void deleteTable(String tableName)throws MasterNotRunningException, ZooKeeperConnectionException, IOException{ 156 // Configuration conf = HBaseConfiguration.create(getConfig()); 157 // HBaseAdmin admin = new HBaseAdmin(conf); 158 // if (admin.tableExists(tableName)){ 159 // admin.disableTable(tableName); 160 // admin.deleteTable(tableName); 161 // }else{ 162 // System.out.println(tableName + "not exist"); 163 // } 164 // admin.close(); 165 // } 166 167 168 169 170 public static Configuration getConfig(){ 171 Configuration configuration = new Configuration(); 172 // conf.set("hbase.rootdir","hdfs:HadoopMaster:9000/hbase"); 173 configuration.set("hbase.zookeeper.quorum", "HadoopMaster:2181,HadoopSlave1:2181,HadoopSlave2:2181"); 174 return configuration; 175 } 176 } 2016-12-11 16:39:36,396 INFO [org.apache.hadoop.hbase.zookeeper.RecoverableZooKeeper] - Process identifier=hconnection-0x7cb96ac0 connecting to ZooKeeper ensemble=HadoopMaster:2181,HadoopSlave1:2181,HadoopSlave2:2181 2016-12-11 16:39:36,413 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT 2016-12-11 16:39:36,413 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:host.name=WIN-BQOBV63OBNM 2016-12-11 16:39:36,413 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:java.version=1.7.0_51 2016-12-11 16:39:36,413 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:java.vendor=Oracle Corporation 2016-12-11 16:39:36,413 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:java.home=C:\Program Files\Java\jdk1.7.0_51\jre 2016-12-11 16:39:36,413 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:java.class.path=D:\Code\MyEclipseJavaCode\HbaseProject\bin;D:\SoftWare\hbase-1.2.3\lib\activation-1.1.jar;D:\SoftWare\hbase-1.2.3\lib\aopalliance-1.0.jar;D:\SoftWare\hbase-1.2.3\lib\apacheds-i18n-2.0.0-M15.jar;D:\SoftWare\hbase-1.2.3\lib\apacheds-kerberos-codec-2.0.0-M15.jar;D:\SoftWare\hbase-1.2.3\lib\api-asn1-api-1.0.0-M20.jar;D:\SoftWare\hbase-1.2.3\lib\api-util-1.0.0-M20.jar;D:\SoftWare\hbase-1.2.3\lib\asm-3.1.jar;D:\SoftWare\hbase-1.2.3\lib\avro-1.7.4.jar;D:\SoftWare\hbase-1.2.3\lib\commons-beanutils-1.7.0.jar;D:\SoftWare\hbase-1.2.3\lib\commons-beanutils-core-1.8.0.jar;D:\SoftWare\hbase-1.2.3\lib\commons-cli-1.2.jar;D:\SoftWare\hbase-1.2.3\lib\commons-codec-1.9.jar;D:\SoftWare\hbase-1.2.3\lib\commons-collections-3.2.2.jar;D:\SoftWare\hbase-1.2.3\lib\commons-compress-1.4.1.jar;D:\SoftWare\hbase-1.2.3\lib\commons-configuration-1.6.jar;D:\SoftWare\hbase-1.2.3\lib\commons-daemon-1.0.13.jar;D:\SoftWare\hbase-1.2.3\lib\commons-digester-1.8.jar;D:\SoftWare\hbase-1.2.3\lib\commons-el-1.0.jar;D:\SoftWare\hbase-1.2.3\lib\commons-httpclient-3.1.jar;D:\SoftWare\hbase-1.2.3\lib\commons-io-2.4.jar;D:\SoftWare\hbase-1.2.3\lib\commons-lang-2.6.jar;D:\SoftWare\hbase-1.2.3\lib\commons-logging-1.2.jar;D:\SoftWare\hbase-1.2.3\lib\commons-math-2.2.jar;D:\SoftWare\hbase-1.2.3\lib\commons-math3-3.1.1.jar;D:\SoftWare\hbase-1.2.3\lib\commons-net-3.1.jar;D:\SoftWare\hbase-1.2.3\lib\disruptor-3.3.0.jar;D:\SoftWare\hbase-1.2.3\lib\findbugs-annotations-1.3.9-1.jar;D:\SoftWare\hbase-1.2.3\lib\guava-12.0.1.jar;D:\SoftWare\hbase-1.2.3\lib\guice-3.0.jar;D:\SoftWare\hbase-1.2.3\lib\guice-servlet-3.0.jar;D:\SoftWare\hbase-1.2.3\lib\hadoop-annotations-2.5.1.jar;D:\SoftWare\hbase-1.2.3\lib\hadoop-auth-2.5.1.jar;D:\SoftWare\hbase-1.2.3\lib\hadoop-client-2.5.1.jar;D:\SoftWare\hbase-1.2.3\lib\hadoop-common-2.5.1.jar;D:\SoftWare\hbase-1.2.3\lib\hadoop-hdfs-2.5.1.jar;D:\SoftWare\hbase-1.2.3\lib\hadoop-mapreduce-client-app-2.5.1.jar;D:\SoftWare\hbase-1.2.3\lib\hadoop-mapreduce-client-common-2.5.1.jar;D:\SoftWare\hbase-1.2.3\lib\hadoop-mapreduce-client-core-2.5.1.jar;D:\SoftWare\hbase-1.2.3\lib\hadoop-mapreduce-client-jobclient-2.5.1.jar;D:\SoftWare\hbase-1.2.3\lib\hadoop-mapreduce-client-shuffle-2.5.1.jar;D:\SoftWare\hbase-1.2.3\lib\hadoop-yarn-api-2.5.1.jar;D:\SoftWare\hbase-1.2.3\lib\hadoop-yarn-client-2.5.1.jar;D:\SoftWare\hbase-1.2.3\lib\hadoop-yarn-common-2.5.1.jar;D:\SoftWare\hbase-1.2.3\lib\hadoop-yarn-server-common-2.5.1.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-annotations-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-annotations-1.2.3-tests.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-client-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-common-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-common-1.2.3-tests.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-examples-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-external-blockcache-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-hadoop2-compat-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-hadoop-compat-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-it-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-it-1.2.3-tests.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-prefix-tree-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-procedure-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-protocol-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-resource-bundle-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-rest-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-server-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-server-1.2.3-tests.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-shell-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\hbase-thrift-1.2.3.jar;D:\SoftWare\hbase-1.2.3\lib\htrace-core-3.1.0-incubating.jar;D:\SoftWare\hbase-1.2.3\lib\httpclient-4.2.5.jar;D:\SoftWare\hbase-1.2.3\lib\httpcore-4.4.1.jar;D:\SoftWare\hbase-1.2.3\lib\jackson-core-asl-1.9.13.jar;D:\SoftWare\hbase-1.2.3\lib\jackson-jaxrs-1.9.13.jar;D:\SoftWare\hbase-1.2.3\lib\jackson-mapper-asl-1.9.13.jar;D:\SoftWare\hbase-1.2.3\lib\jackson-xc-1.9.13.jar;D:\SoftWare\hbase-1.2.3\lib\jamon-runtime-2.4.1.jar;D:\SoftWare\hbase-1.2.3\lib\jasper-compiler-5.5.23.jar;D:\SoftWare\hbase-1.2.3\lib\jasper-runtime-5.5.23.jar;D:\SoftWare\hbase-1.2.3\lib\javax.inject-1.jar;D:\SoftWare\hbase-1.2.3\lib\java-xmlbuilder-0.4.jar;D:\SoftWare\hbase-1.2.3\lib\jaxb-api-2.2.2.jar;D:\SoftWare\hbase-1.2.3\lib\jaxb-impl-2.2.3-1.jar;D:\SoftWare\hbase-1.2.3\lib\jcodings-1.0.8.jar;D:\SoftWare\hbase-1.2.3\lib\jersey-client-1.9.jar;D:\SoftWare\hbase-1.2.3\lib\jersey-core-1.9.jar;D:\SoftWare\hbase-1.2.3\lib\jersey-guice-1.9.jar;D:\SoftWare\hbase-1.2.3\lib\jersey-json-1.9.jar;D:\SoftWare\hbase-1.2.3\lib\jersey-server-1.9.jar;D:\SoftWare\hbase-1.2.3\lib\jets3t-0.9.0.jar;D:\SoftWare\hbase-1.2.3\lib\jettison-1.3.3.jar;D:\SoftWare\hbase-1.2.3\lib\jetty-6.1.26.jar;D:\SoftWare\hbase-1.2.3\lib\jetty-sslengine-6.1.26.jar;D:\SoftWare\hbase-1.2.3\lib\jetty-util-6.1.26.jar;D:\SoftWare\hbase-1.2.3\lib\joni-2.1.2.jar;D:\SoftWare\hbase-1.2.3\lib\jruby-complete-1.6.8.jar;D:\SoftWare\hbase-1.2.3\lib\jsch-0.1.42.jar;D:\SoftWare\hbase-1.2.3\lib\jsp-2.1-6.1.14.jar;D:\SoftWare\hbase-1.2.3\lib\jsp-api-2.1-6.1.14.jar;D:\SoftWare\hbase-1.2.3\lib\junit-4.12.jar;D:\SoftWare\hbase-1.2.3\lib\leveldbjni-all-1.8.jar;D:\SoftWare\hbase-1.2.3\lib\libthrift-0.9.3.jar;D:\SoftWare\hbase-1.2.3\lib\log4j-1.2.17.jar;D:\SoftWare\hbase-1.2.3\lib\metrics-core-2.2.0.jar;D:\SoftWare\hbase-1.2.3\lib\netty-all-4.0.23.Final.jar;D:\SoftWare\hbase-1.2.3\lib\paranamer-2.3.jar;D:\SoftWare\hbase-1.2.3\lib\protobuf-java-2.5.0.jar;D:\SoftWare\hbase-1.2.3\lib\servlet-api-2.5.jar;D:\SoftWare\hbase-1.2.3\lib\servlet-api-2.5-6.1.14.jar;D:\SoftWare\hbase-1.2.3\lib\slf4j-api-1.7.7.jar;D:\SoftWare\hbase-1.2.3\lib\slf4j-log4j12-1.7.5.jar;D:\SoftWare\hbase-1.2.3\lib\snappy-java-1.0.4.1.jar;D:\SoftWare\hbase-1.2.3\lib\spymemcached-2.11.6.jar;D:\SoftWare\hbase-1.2.3\lib\xmlenc-0.52.jar;D:\SoftWare\hbase-1.2.3\lib\xz-1.0.jar;D:\SoftWare\hbase-1.2.3\lib\zookeeper-3.4.6.jar 2016-12-11 16:39:36,414 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:java.library.path=C:\Program Files\Java\jdk1.7.0_51\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\ProgramData\Oracle\Java\javapath;C:\Python27\;C:\Python27\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;D:\SoftWare\MATLAB R2013a\runtime\win64;D:\SoftWare\MATLAB R2013a\bin;C:\Program Files (x86)\IDM Computer Solutions\UltraCompare;C:\Program Files\Java\jdk1.7.0_51\bin;C:\Program Files\Java\jdk1.7.0_51\jre\bin;D:\SoftWare\apache-ant-1.9.0\bin;HADOOP_HOME\bin;D:\SoftWare\apache-maven-3.3.9\bin;D:\SoftWare\Scala\bin;D:\SoftWare\Scala\jre\bin;%MYSQL_HOME\bin;D:\SoftWare\MySQL Server\MySQL Server 5.0\bin;D:\SoftWare\apache-tomcat-7.0.69\bin;%C:\Windows\System32;%C:\Windows\SysWOW64;D:\SoftWare\SSH Secure Shell;. 2016-12-11 16:39:36,414 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:java.io.tmpdir=C:\Users\ADMINI~1\AppData\Local\Temp\ 2016-12-11 16:39:36,415 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:java.compiler=<NA> 2016-12-11 16:39:36,415 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:os.name=Windows 7 2016-12-11 16:39:36,415 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:os.arch=amd64 2016-12-11 16:39:36,415 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:os.version=6.1 2016-12-11 16:39:36,415 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:user.name=Administrator 2016-12-11 16:39:36,415 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:user.home=C:\Users\Administrator 2016-12-11 16:39:36,415 INFO [org.apache.zookeeper.ZooKeeper] - Client environment:user.dir=D:\Code\MyEclipseJavaCode\HbaseProject 2016-12-11 16:39:36,417 INFO [org.apache.zookeeper.ZooKeeper] - Initiating client connection, connectString=HadoopMaster:2181,HadoopSlave1:2181,HadoopSlave2:2181 sessionTimeout=90000 watcher=hconnection-0x7cb96ac00x0, quorum=HadoopMaster:2181,HadoopSlave1:2181,HadoopSlave2:2181, baseZNode=/hbase 2016-12-11 16:39:36,504 INFO [org.apache.zookeeper.ClientCnxn] - Opening socket connection to server HadoopSlave1/192.168.80.11:2181. Will not attempt to authenticate using SASL (unknown error) 2016-12-11 16:39:36,511 INFO [org.apache.zookeeper.ClientCnxn] - Socket connection established to HadoopSlave1/192.168.80.11:2181, initiating session 2016-12-11 16:39:36,527 INFO [org.apache.zookeeper.ClientCnxn] - Session establishment complete on server HadoopSlave1/192.168.80.11:2181, sessionid = 0x25872b4d2c50026, negotiated timeout = 40000test_table3exist 2016-12-11 16:39:38,139 INFO [org.apache.hadoop.hbase.client.ConnectionManager$HConnectionImplementation] - Closing zookeeper sessionid=0x25872b4d2c50026 2016-12-11 16:39:38,156 INFO [org.apache.zookeeper.ZooKeeper] - Session: 0x25872b4d2c50026 closed 2016-12-11 16:39:38,156 INFO [org.apache.zookeeper.ClientCnxn] - EventThread shut down 本文转自大数据躺过的坑博客园博客,原文链接:http://www.cnblogs.com/zlslch/p/6159765.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

Hadoop MapReduce编程 API入门系列之wordcount版本2(六)

代码 1 package zhouls.bigdata.myMapReduce.wordcount4; 2 3 import java.io.IOException; 4 5 import org.apache.hadoop.io.IntWritable; 6 import org.apache.hadoop.io.LongWritable; 7 import org.apache.hadoop.io.Text; 8 import org.apache.hadoop.mapreduce.Mapper; 9 import org.apache.hadoop.util.StringUtils; 10 11 public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable>{ 12 13 //该方法循环调用,从文件的split中读取每行调用一次,把该行所在的下标为key,该行的内容为value 14 protected void map(LongWritable key, Text value, 15 Context context) 16 throws IOException, InterruptedException { 17 String[] words = StringUtils.split(value.toString(), ' '); 18 for(String w :words){ 19 context.write(new Text(w), new IntWritable(1)); 20 } 21 } 22 } 1 package zhouls.bigdata.myMapReduce.wordcount4; 2 3 import java.io.IOException; 4 5 import org.apache.hadoop.io.IntWritable; 6 import org.apache.hadoop.io.Text; 7 import org.apache.hadoop.mapreduce.Reducer; 8 9 public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable>{ 10 11 //每组调用一次,这一组数据特点:key相同,value可能有多个。 12 protected void reduce(Text arg0, Iterable<IntWritable> arg1, 13 Context arg2) 14 throws IOException, InterruptedException { 15 int sum =0; 16 for(IntWritable i: arg1){ 17 sum=sum+i.get(); 18 } 19 arg2.write(arg0, new IntWritable(sum)); 20 } 21 } //System.setProperty("HADOOP_USER_NAME", "root"); // //1、MR执行环境有两种:本地测试环境,服务器环境 // //本地测试环境(windows):(便于调试) // 在windows的hadoop目录bin目录有一个winutils.exe // 1、在windows下配置hadoop的环境变量 // 2、拷贝debug工具(winutils.exe)到HADOOP_HOME/bin // 3、修改hadoop的源码 ,注意:确保项目的lib需要真实安装的jdk的lib // // 4、MR调用的代码需要改变: // a、src不能有服务器的hadoop配置文件(因为,本地是调试,去服务器环境集群那边的) // b、再调用是使用: // Configuration config = new Configuration(); // config.set("fs.defaultFS", "hdfs://HadoopMaster:9000"); // config.set("yarn.resourcemanager.hostname", "HadoopMaster"); //服务器环境:(不便于调试),有两种方式。 //首先需要在src下放置服务器上的hadoop配置文件(都要这一步) //1、在本地直接调用,执行过程在服务器上(真正企业运行环境) // a、把MR程序打包(jar),直接放到本地 // b、修改hadoop的源码 ,注意:确保项目的lib需要真实安装的jdk的lib // c、增加一个属性: // config.set("mapred.jar", "C:\\Users\\Administrator\\Desktop\\wc.jar"); // d、本地执行main方法,servlet调用MR。 // // //2、直接在服务器上,使用命令的方式调用,执行过程也在服务器上 // a、把MR程序打包(jar),传送到服务器上 // b、通过: hadoop jar jar路径 类的全限定名 // // // // //a,1 b,1 //a,3 c,3 //a,2 d,2 // // //a,3 c,3 //a,2 d,2 //a,1 b,1 // 1 package zhouls.bigdata.myMapReduce.wordcount4; 2 3 4 import org.apache.hadoop.conf.Configuration; 5 import org.apache.hadoop.fs.FileSystem; 6 import org.apache.hadoop.fs.Path; 7 import org.apache.hadoop.io.IntWritable; 8 import org.apache.hadoop.io.Text; 9 import org.apache.hadoop.mapreduce.Job; 10 import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; 11 import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; 12 13 public class RunJob { 14 15 public static void main(String[] args) { 16 Configuration config =new Configuration(); 17 config.set("fs.defaultFS", "hdfs://HadoopMaster:9000"); 18 config.set("yarn.resourcemanager.hostname", "HadoopMaster"); 19 // config.set("mapred.jar", "C:\\Users\\Administrator\\Desktop\\wc.jar");//先打包好wc.jar 20 try { 21 FileSystem fs =FileSystem.get(config); 22 23 Job job =Job.getInstance(config); 24 job.setJarByClass(RunJob.class); 25 26 job.setJobName("wc"); 27 28 job.setMapperClass(WordCountMapper.class); 29 job.setReducerClass(WordCountReducer.class); 30 31 job.setMapOutputKeyClass(Text.class); 32 job.setMapOutputValueClass(IntWritable.class); 33 34 FileInputFormat.addInputPath(job, new Path("/usr/input/wc/wc.txt"));//新建好输入路径,且数据源 35 36 Path outpath =new Path("/usr/output/wc"); 37 if(fs.exists(outpath)){ 38 fs.delete(outpath, true); 39 } 40 FileOutputFormat.setOutputPath(job, outpath); 41 42 boolean f= job.waitForCompletion(true); 43 if(f){ 44 System.out.println("job任务执行成功"); 45 } 46 } catch (Exception e) { 47 e.printStackTrace(); 48 } 49 } 50 } 本文转自大数据躺过的坑博客园博客,原文链接:http://www.cnblogs.com/zlslch/p/6163585.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

Objective-C编程中的数字类型(NSInteger,NSUInteger,NSNumber)

在Objective-C中,我们可以使用c中的数字数据类型,int、float、long等。它们都是基本数据类型,而不是对象。也就是说,不能够向它们发送消息。然后,有些时候需要将这些值作为对象使用。 NSInteger、NSUInteger 当你不知道程序运行哪种处理器架构时,你最好使用NSInteger,因为在有可能int在32位系统中只是int类型,而在64位系统,int可能变是long型。除非不得不使用int/long型,否则推荐使用NSInteger。 从上面的定义可以看出NSInteger/NSUInteger是一种动态定义的类型,在不同的设备,不同的架构,有可能是int类型,有可能是long类型。NSUInteger是无符号的,即没有负数,NSInteger是有符号的。 NSNumber 有人说既然都有了NSInteger等这些基础类型了为什么还要有NSNumber?NSNumber可以将基本数据类型包装起来,形成一个对象,这样就可以给其发送消息,装入NSArray中等。 1 2 3 4 5 6 NSIntegerintVal=123; NSNumber*numberVal=[NSNumbernumberWithInteger:intVal]; NSMutableArray*array=[NSMutableArrayarray]; [arrayaddObject:intVal]; //错误,intVal不是一个对象类型 [arrayaddObject:numberVal]; //正确 Cocoa提供了NSNumber类来包装(即以对象形式实现)基本数据类型。 +(NSNumber*)numberWithChar:(char)value;+(NSNumber*)numberWithInt:(int)value;+(NSNumber*)numberWithDouble:(double)value;+(NSNumber*)numberWithFloat:(float)value;+(NSNumber*)numberWithBool:(BOOL)value;... 将基本类型数据封装到NSNumber中后,就可以通过下面的实例方法重新获取它: -(char)charValue;-(int)intValue;-(float)floatValue;-(double)doubleValue;-(BOOL)boolValue;... NSValue类 但是我们往往也会有这样的需求,例如需要将CGPoint 或是CGRect这样的结构存储在集合中.一个NSValue对象是用来存储一个C或者Objective-C数据的简单容器。它可以保存任意类型的数 据,比如int,float,char,当然也可以是指pointers, structures, and object ids。NSValue类的目标就是允许以上数据类型的数据结构能够被添加到集合里.这种结构转化为对象的方式,不就是java中的装箱(boxing) 吗?不过在Objective-C中称为包装(wraping),相反的,从对象中解出基本类型,称为展开(unwraping),在java中叫拆箱 (unboxing). NSNumber 继承自NSObject,可使用compare、isEqual等消息。 NSNumber是NSValue的子类。NSValue可包装任意类型值。 本文转自朱先忠老师51CTO博客,原文链接:http://blog.51cto.com/zhuxianzhong/1598644,如需转载请自行联系原作者

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码