首页 文章 精选 留言 我的

精选列表

搜索[webpack入门],共10000篇文章
优秀的个人博客,低调大师

【Java入门提高篇】Day17 Java异常处理(下)

今天继续讲解java中的异常处理机制,主要介绍Exception家族的主要成员,自定义异常,以及异常处理的正确姿势。 Exception家族 一图胜千言,先来看一张图。 Exception这是一个父类,它有两个儿子,IOException和RuntimeException,每个儿子都很能生,所以它有着一堆的孙子,但其实,Exception家族还有一个大家伙,那就是Throwable,这是一个接口,看名字就知道意思,就是“可被抛出”嘛,它还有一个同父异母的哥哥,那就是Error,这家伙可厉害了,Error类一般是指与虚拟机相关的问题,如系统崩溃,虚拟机错误,内存空间不足,方法调用栈溢出等。catch语句里,不仅可以catch住Exception,还能catch住Error(什么?你真的打算catchError??程独秀同学,你先坐下。)一般情况下,是不能捕获Error的,对于这类错误,Java编译器不去检查他们。对于这类错误的导致的应用程序中断,仅靠程序本身无法恢复和预防,遇到这样的错误,建议让程序终止。除非你有把握能正确处理,否则程独秀同学还是坐下吧(滑稽)。 UncheckedException和CheckedException 你也许会一脸懵逼,???,这是啥?异常也是分派别的,Unchecked Exception表示“未检查异常“,CheckedException自然就是”已检查异常“,派生于Error或者RuntimeException的异常称为unchecked异常,所有其他的异常成为checked异常。那问题来了,为啥要区分这两种异常? 我们可以再看看上面那个图,可以看出,RuntimeException和Error都是由程序内部引发的错误,比如上一篇里所说的空指针和算术异常。而CheckedException则大都是由外部因素导致的,如文件无法找到异常,这是虚拟机无法掌控的情况,当出现异常,虚拟机也只能一脸懵逼,不知道该如何是好,所以当有可能发生时,就必须要使用try..catch去捕获它,而对于Unchecked Exception时,大部分是由于代码引发的,所以只要代码写的足够完善,是不会抛出这样的异常的,所以也不强制要求捕获。 所以原因其实很简单,编译器将检查你是否为所有的已检查异常提供了异常处理机制,比如说我们使用Class.forName()来查找给定的字符串的class对象的时候,如果没有为这个方法提供异常处理,编译是无法通过的。已检查异常的意义就在于让你知道,这地方是有可能抛异常的,你要注意了,赶紧捕获了。 自定义异常 那么如何自定义一个异常呢?其实很简单,只需要继承Exception类就好了。看下面的栗子: public class MyException extends Exception { public MyException() { super(); } public MyException(String message) { super(message); } public MyException(String message, Throwable cause) { super(message, cause); } public MyException(Throwable cause) { super(cause); } protected MyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } } MyException继承了Exception类,重写了构造函数,并没有加自己的逻辑,只是调用了父类的方法。你看,自定义一个异常其实很简单吧。看到这你也许又疑惑了,这尼玛好像就是给Exception换了个名字,有啥用??? 别急,别急,你忘了吗,Exception不仅是可以捕获的,还是可以主动抛出的,所以当遇到某些特定的情况时,我们就可以主动抛出异常,然后在调用时去捕获它,获取异常信息,如果直接用Exception的话,那么捕获的时候,会把所有的异常,该捕获不该捕获的都一起捕获了,那么就没法区分哪些是我们主动抛出来的异常了,这样就无法对那些异常进行特殊处理了。 异常处理的正确姿势 接下来要简单介绍一个实际使用中常用的异常处理方法——异常链化处理。 在一些大型的,模块化的软件开发中,一旦一个地方发生异常,则如骨牌效应一样,将导致出现一连串的异常。假设B模块需要调用A模块的方法,如果A模块发生异常,则B也将不能完成而发生异常,但是B在抛出异常时,会将A的异常信息掩盖掉,这将使得异常的根源信息丢失。而使用异常的链化可以将多个模块的异常串联起来,使得异常信息不会丢失。 异常链化就是用一个异常对象为参数构造新的异常对象。新的异对象将包含先前异常的信息。这项技术主要是异常类的一个带Throwable参数的函数来实现的。这个当做参数的异常,我们叫他根源异常(cause)。如果你细心一点的话,会发现上面的栗子里也有一个叫做cause的东西,没错,说的其实就是它,在new一个新的异常时,将之前的异常信息传入构造函数即可。下面再用一个简单的栗子进行说明: public class Test { public static void main(String[] args) { System.out.println("请输入2个加数"); int result; try { result = add(); System.out.println("结果:"+result); } catch (Exception e){ e.printStackTrace(); } } /** * 执行加法计算 */ private static int add() throws Exception { int result; try { List<Integer> nums =getInputNumbers(); result = nums.get(0) + nums.get(1); }catch(InputMismatchException immExp){ //链化:以一个异常对象为参数构造新的异常对象。 throw new Exception("计算失败",immExp); } return result; } /** * 获取输入的整数 */ private static List<Integer> getInputNumbers() { List<Integer> nums = new ArrayList<>(); Scanner scan = new Scanner(System.in); try { int num1 = scan.nextInt(); int num2 = scan.nextInt(); nums.add(new Integer(num1)); nums.add(new Integer(num2)); }catch(InputMismatchException immExp){ throw immExp; }finally { scan.close(); } return nums; } } 输出如下: 请输入2个加数 d d java.lang.Exception: 计算失败 at com.frank.chapter17.Test.add(Test.java:35) at com.frank.chapter17.Test.main(Test.java:18) Caused by: java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at com.frank.chapter17.Test.getInputNumbers(Test.java:47) at com.frank.chapter17.Test.add(Test.java:31) ... 1 more 可以看到,当输入的不是整数时,发生了异常,在getInputNumbers方法里没有处理这个异常,而是将它继续抛出,在add方法里捕获了异常之后,以该异常为构造参数,重新抛出了一个异常,从打印输出的信息可以看到,不仅仅有第二次抛出的异常信息,第一次的输出信息不匹配异常的详细信息也包含在了里面,衔接在Causedby之后,形成了一条异常链,这样可以方便我们更快的排查问题所在。 至此,异常就讲解完毕了,希望能给大家带来一些启发和思考,如果觉得还算ok的话,记得动动小手点推荐,让更多人可以看到,也欢迎关注我的博客,会持续更新的。如果有什么讲的不好的地方。。。emmmmmm,你倒是来打我呀(逃) 真正重要的东西,用眼睛是看不见的。

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

【Java入门提高篇】Day16 Java异常处理(上)

当当当当当当,各位看官,好久不见,甚是想念。 今天我们来聊聊Java里的一个小妖精,那就是异常。 什么是异常?什么是异常处理? 异常嘛,顾名思义就是不正常,(逃),是Java程序运行时,发生的预料之外的事情,它阻止了程序按照程序员的预期正常执行。 异常处理,应该说异常处理机制,就是专门用来制服这个小妖精的法宝。Java中的异常处理机制能让程序在异常发生时,按照代码的预先设定的异常处理逻辑,针对性地处理异常,让程序尽最大可能恢复正常并继续执行,且保持代码的清晰。 简而言之,Java异常处理就是能让我们主动迎击可能到来的异常,并将它们以圆润的方式处理掉。 还是先来看个小栗子,看看java里的异常长什么样。 public class Test { public static void main(String args[]){ int i = 0 / 0; System.out.println("i = " + i); } } 别慌别慌,不要看到红色提示就内心崩溃只想关掉IDE,来,抓紧我的手,带你看清“异常”这个磨人的小妖精的真面目(滑稽)。 代码里将0作为了分母,因此程序会发生算术异常,抛出一个异常后,如果没有任何处理,默认会终止程序,所以后面的打印内容并没有输出。在异常内容里,有说明异常类型为:java.lang.ArithmeticException,也就是算术异常,后面跟着的是异常原因: / by zero,也就是说异常出现的原因是将0作为了分母,而且后面还有堆栈信息,指出了异常抛出的位置是在com.frank.chapter16.main.Test.main这个包下,Test类的第11行(这个行数如果跟你想的不一样,不要在意,因为我的代码开始之前还有一些不可描述的说明信息),因为只有一次方法调用,所以没有很长的堆栈信息,看起来也很简洁明了。 所以你看,其实异常也没那么可怕吧,不仅给了异常原因,还告诉了你这个bug是出在第几行,所以好好利用它,可以帮助你写出更难以发现的bug,呸,说错了,可以帮助你更容易找到bug(手动滑稽)。 如果不希望抛出异常后程序就结束,而是希望它继续运行呢?那么就捕获它。 如何使用异常处理 我们来把上面那个栗子改改: public class Test { public static void main(String args[]){ try{ int i = 0 / 0; }catch (Exception e){ System.out.println("好像发生异常了,但是我不管,我还要继续运行"); } System.out.println("运行完毕!"); } } 输出如下: 好像发生异常了,但是我不管,我还要继续运行 运行完毕! 好的,很强势,现在即使抛出了异常,程序也继续运行了。异常就像是一头野兽,但你一旦捕获它,驯服它,就可以为你所用,为所欲为了。 try...catch...是常用的异常处理搭配,如果在try语句块中发生了异常,如果刚好这个异常被捕获到了,那么会直接跳到catch语句块中,执行catch语句中的代码,像上面的栗子里,因为对Exception类进行了捕获处理,所以当它的子类异常java.lang.ArithmeticException被抛出来的时候,也能捕获它。关于Exception类的结构层次关系,后面再做详细介绍。 还有另外一种搭配方式,那就是try...catch...finally,finally语句块比catch要强势的多,前面说了catch语句块必须要捕获到了特定的Exception才会执行里面的代码,如果catch的是ArithmeticException但是抛出的却是空指针异常,那就不会被捕获了,异常也就逃之夭夭了。这个时候,finally的优势就展示出来了,不管抛出什么样的异常,也不管是否抛出了异常,finally中的代码都会被执行。所以一般的用法是在finally语句块里释放掉那些需要被释放的资源,如socket连接,关闭io流,关闭数据库连接等等。也就是说一般在finally中收拾try中抛出的烂摊子,心疼一秒finally,果然能者多劳啊。 当然,try...finally这样的搭配也是ok的,需要注意的是,当try语句中发生了异常之后,在发生异常处之后的代码将不会再执行,而是跳到相应的catchu或者finally中去。 public class Test { public static void main(String args[]){ try{ int i = 0 / 0; }catch (NullPointerException e) { System.out.println("这里捕获空指针异常"); }catch (ArithmeticException e){ System.out.println("这里捕获算术异常"); }finally { System.out.println("这里是finally"); } System.out.println("运行完毕!"); } } 输出如下: 这里捕获算术异常 这里是finally 运行完毕! 在上面的代码中,catch语句块是可以同时使用多个的,第一个catch语句块捕获的是空指针异常,但由于抛出的是算术异常,所以没有捕获住,但被第二个catch捕获到了,所以第二个catch语句块中的代码执行了。异常匹配是按照从上到下的顺序进行匹配的,最后才执行finally中的代码块。关于try...catch...finally,还有一个很有趣的return问题,如果三个语句块里都有return,最终返回结果会是怎样呢?这里做了详细的说明,http://www.cnblogs.com/mfrank/p/7895660.html 有兴趣的话可以看一看。 绝大多数情况下,finally中的代码都是会被执行的,只有一种情况下,finally中的代码不会被执行,那就是在try语句块中结束掉了虚拟机(如:使用 System.exit(0); )。 关于异常,还有一个关键字需要介绍,那就是throw,使用throw可以主动抛出一个异常。看到这你也许会一脸懵逼,主动抛出???嫌异常不够多,凑热闹不嫌事大??别急别急,中间一定有什么误会,把刀放下,有话好好说。 throw关键字确实是用来抛出异常的,你可以这样使用: public class Test { public static void main(String args[]){ try{ throw new NullPointerException("听说你很闲,给你抛个异常。"); }catch (NullPointerException e) { System.out.println("这里捕获空指针异常,提示内容:" + e.getMessage()); e.printStackTrace(); } } } 输出如下: 这里捕获空指针异常,提示内容:听说你很闲,给你抛个异常。 java.lang.NullPointerException: 听说你很闲,给你抛个异常。 at com.frank.chapter16.main.Test.main(Test.java:11) 用throw关键字可以抛出任意类型的异常,当然,你想的话,还有抛Error,至于什么是Error,已经跟Exception的关系,将在下一篇里进行讲解。暂时不用深究。 在throw异常的时候,可以加上抛出异常的原因,这样可以更方便定位问题所在,当然,一般来说不会像栗子中这样使用的,这里只是为了简单起见。 到此为止,异常的上半篇已经讲解完毕,在这一篇里,说明了什么是异常,什么是异常处理,以及如何使用异常处理机制。相信大家对这个小妖精有了初步的认识,下一篇中,将会讲解Exception家族都有哪些成员,如何使用自定义异常,已经异常处理的实际使用中的正确姿势。欢迎大家继续关注,之后计划每周两篇以上的更新,如果有讲解遗漏或者不好的地方,欢迎大家及时指出,共同进步! 真正重要的东西,用眼睛是看不见的。

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

【入门必备】史上最全的深度学习资源汇总,速藏!

目录: 介绍 教程视频数据集项目论文 介绍: 作为传统机器学习重要的一个分支,与机器学习算法相比,深度学习算法最大的特点是至少含有一个隐藏层的神经网络(NN)。此外,深度学习的分层处理的思想也大大提高了模型的泛化能力。深度学习发展到今天,大致分为以下一些比较流行的网络结构:深度神经网络(DNN)、卷积神经网络(CNN)、循环神经网络(RNN)、生成对抗网络(GAN)等。应用最广的几个研究领域分别是自然语言处理、语音识别和图像处理。出现了Tensorflow、Keras、Caffe、Torch等技术框架。深度学习近年来发展迅猛,在国内外都引起了广泛的关注,也吸引了越来越多的人投身于深度学习领域的研究。今天小编有幸为大家介绍一些我自认为不错的深度学习资源,希望帮助热爱深度学习的小伙伴能够走的更远。 教程: Topal的深度学习教程,从感

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

带你入门Python数据挖掘与机器学习(附代码、实例)

一、数据挖掘与机器学习技术简介 什么是数据挖掘?数据挖掘指的是对现有的一些数据进行相应的处理和分析,最终得到数据与数据之间深层次关系的一种技术。例如在对超市货品进行摆放时,牛奶到底是和面包摆放在一起销量更高,还是和其他商品摆在一起销量更高。数据挖掘技术就可以用于解决这类问题。具体来说,超市的货品摆放问题可以划分为关联分析类场景。 在日常生活中,数据挖掘技术应用的非常广泛。例如对于商户而言,常常需要对其客户的等级(svip、vip、普通客户等)进行划分,这时候可以将一部分客户数据作为训练数据,另一部分客户数据作为测试数据。然后将训练数据输入到模型中进行训练,在训练完成后,输入另一部分数据进行测试,最终实现客户等级的自动划分。其他类似的应用例子还有验证码识别、水果品质自动筛选等。 那么机器学习技术又是什么呢?一言以蔽之,凡是让机器通过我们所

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

Python3快速入门——(7)迭代(iterable)和迭代器

迭代(iterable) #任何可迭代对象都可以作用于for循环,包括我们自定义的数据类型,只要符合迭代条件,就可以使用for循环 d = { 'a' : 1 , 'b' : 2 , 'c' : 3 } #对dict迭代 for k,v in d.items(): # 如果要同时迭代key和value,可以用for k, v in d.items() print (k,v) #默认情况下,dict迭代的是key # 如果要迭代value,可以用for value in d.values() #字符串也是可迭代对象,因此,也可以作用于for循环 #如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断 from collections import Iterable #导入collections模块的Iterable类型 n= isinstance (d,Iterable) print (n) #结果为True,可迭代 #Python内置的 enumerate 函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身 names=[ 'a' , 'b' , 'c' , 'd' ] for i,value in enumerate (names): #for循环同时引用两个变量 print (i,value) for x,y in [( 1 , 2 ),( 3 , 5 ),( 5 , 6 )]: ##for循环同时引用两个变量 print (x,y) 迭代器 可以直接作用于 for 循环的数据类型有以下几种: 一类是 集合数据类型 ,如 list 、 tuple 、 dict 、 set 、 str 等; 一类是 generator ,包括生成器和带 yield 的generator function。 这些可以直接作用于 for 循环的对象统称为可迭代对象: Iterable #可以使用isinstance()判断一个对象是否是Iterable对象 from collections import Iterable m= isinstance ([],Iterable) #True #而生成器不但可以作用于for循环,还可以被next()函数不断调用并返回下一个值, # 直到最后抛出StopIteration错误表示无法继续返回下一个值了。 #可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator #生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。 #把list、dict、str等Iterable变成Iterator可以使用iter()函数 from collections import Iterator m= isinstance ( iter ( 'abc' ),Iterator) #True 凡是可作用于 for 循环的对象都是 Iterable 类型; 凡是可作用于 next() 函数的对象都是 Iterator 类型,它们表示一个惰性计算的序列; 集合数据类型如 list 、 dict 、 str 等是 Iterable 但不是 Iterator ,不过可以通过 iter() 函数获得一个 Iterator 对象。 Python的 for 循环本质上就是通过不断调用 next() 函数实现的

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

Python3快速入门——(4)循环结构和判断结构

循环结构 #循环结构 cities=[ "Austin" , "Dallas" , "Houston" ] for city in cities: #for循环 print (city) #通过缩进控制整体结构 i= 0 while i< 3 : #while循环 i+= 1 print (i) for j in range ( 10 ): #range(n)表示从0到n-1的n个数 print (j) cities=[[ "Austin" , "Dallas" , "Houston" ],[ "Haerbin" , "Shanghai" , "Beijing" ]] #list中的元素仍是list for city in cities: print (city) #输出list中的两个list元素 for i in cities: #两层for循环输出两个list中的每个元素 for j in i: print (j) #注意: 如果代码写得有问题,会让程序陷入“死循环”,也就是永远循环下去。这时可以用 Ctrl+C 退出程序,或者强制结束Python进程。 #注意 : Python提供一个 range() 函数,可以生成一个整数序列,再通过 list() 函数可以转换为list #例如: list ( range (5)) 结果为:[0, 1, 2, 3, 4] 判断结构 #选择结构 cat= True #bool类型值 dog= False print ( type (cat)) #<class 'bool'> print ( 8 == 8 ) #True 判断语句 print ( 8 != 8 ) #False print ( 10 >= 5 ) #True sample_rate= 700 if (sample_rate> 50 ): #if语句选择 print (sample_rate) else : print ( 'less lan' )

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

Python入门(二)快捷键、操作符和BIF

快捷键(常用) 新建文件:Ctrl+N; 打开文件:Ctrl+O; 打开模块:Alt+M(先选中模块,再按下此快捷键,会打开该模块的python源码); 浏览模块:Alt+C; 路径浏览: Alt+FP; 光标当前所在行列:IDLE右下角有显示; 跳到目标行号:Alt+G; 调出上一条命令:Alt+P; 调出下一条命令: Alt+N; 跳到开头:Ctrl+uparrow; 跳到结尾:Ctrl+downarrow; 跳到上一行开头:Ctrl+leftarrow; 跳到下一行开头:Ctrl+rightarrow; 全选:Ctrl+A; 缩进代码:Tab/空格(注意:这两种方式缩进量可能不同,会导致运行时会报错“unexpected indent”,所以,编程时最好只采取一种;如果已经混用,可以在编程结束后,先Ctrl+A、再Alt+5/6、再OK,三步即可解决); 补齐文中出现过的单词:Alt+/; 查找:Ctrl+F; 再次查找:Ctrl+G; 查找选中部分:Ctrl+F3; 查找文件:Alt+F3; 替换:Ctrl+H; 撤销:Ctrl+Z; 反撤销:Ctrl+Shift+Z; 注释代码行:Alt+3; 取消注释代码行:Alt+4; 全选:Ctrl+A; 运行代码:F5; 保存代码:Ctrl+S; 另存为:Ctrl+Shift+S; 保存副本:Alt+Shift+S; 打印窗口:Ctrl+P; 关闭:Alt+F4; 退出:Ctrl+Q; 打开Python文件:F1; 单步调试:Alt+DD; 定位到错误位置:Alt+DG(先定位到错误行,再按下此快捷键); 显示错误历史:Alt+DA; 重新启动shell:Ctrl+F6 。 操作符 按优先级由高到底排列: 幂运算[**]; 正负号[+ -]; 算数操作符[* / // % + -]; 比较操作符[< <= > >= == != <>]; 逻辑运算符 not and or 。 注:编程时适当使用(),可增加程序的可读性。 BIF Built-in functions的缩写,意为内置函数,编程时通过使用内置函数实现各种功能。本文不具体分析每个BIF的具体使用,只说明查找BIF功能的方法,具体使用会在以后的文章中结合实例分析。 在IDLE中输入: dir(__builtins__) 显示如下列表,其中全都为小写的字符串为BIF。 如果想知道某个BIF的功能,直接在IDLE内查找即可(这里以super()函数为例),输入以下代码: help(super) super()函数的功能及使用方法显示如下: 如果有些英文看不懂,可以借助翻译软件。 有了以上了解,不禁发现Python和MATLAB有很多相似之处,这里借助奥特曼超人很久之前的一段话,浅略地对两者进行比较: 国外近几年比较流行的是MATLAB,但它是商用,和Oracle一样,需要付费,且价格不菲。如果使用Python做科学计算,一方面完全免费,同时众多开源的科学计算库都提供了Python的调用接口,用户可以在任何计算机上免费安装Python及其绝大多数的扩展库;其次Python是一门更易学、更严谨的程序设计语言,它能让用户编写出更易读、易维护的代码;最后Python有着丰富的扩展库,可以轻易完成各种高级任务,开发者可以用Python实现完整应用程序所需的各种功能。 END!

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

【Elasticsearch全文搜索引擎实战】之Filebeat快速入门

0. 背景 用过ELK(Elasticsearch, Logstash, Kibana)的人应该都面临过同样的问题,Logstash虽然功能强大:支持许多的input/output plugin、强大的filter功能。但是确内存占用会非常大。还有种情况(我就是orz...),在Logstash 5.2+版本中,input plugin使用Log4j,必须使用filebeat,并且只支持log4j 1.x版本。了解到filebeat已经支持filter和不少的output plugin,果断转投fielbeat阵营。 1. 简介 Filebeat官方介绍是这样的: Filebeat is a log data shipper for local files. Installed as an agent on your servers, Filebeat monitors the log directories or specific log files, tails the files, and forwards them either to Elasticsearch or Logstash for indexing. Here’s how Filebeat works: When you start Filebeat, it starts one or more prospectors that look in the local paths you’ve specified for log files. For each log file that the prospector locates, Filebeat starts a harvester. Each harvester reads a single log file for new content and sends the new log data to libbeat, which aggregates the events and sends the aggregated data to the output that you’ve configured for Filebeat. 翻译成中文大意就是: Filebeat是一个日志数据收集工具,在服务器上安装客户端后,filebeat会监控日志目录或者指定的日志文件,追踪读取这些文件(追踪文件的变化,不停的读),并且转发这些信息到elasticsearch或者logstarsh中存放。 以下是filebeat的工作流程:当你开启filebeat程序的时候,它会启动一个或多个探测器(prospectors)去检测你指定的日志目录或文件,对于探测器找出的每一个日志文件,filebeat启动收割进程(harvester),每一个收割进程读取一个日志文件的新内容,并发送这些新的日志数据到处理程序(spooler),处理程序会集合这些事件,最后filebeat会发送集合的数据到你指定的地点。 更关于探测器(prospectors)和收割进程(harvester)信息,请查看官网How Filebeat works. 1.2 核心功能 1.2.1 性能稳健,不错过任何检测信号 无论在任何环境中,随时都潜伏着应用程序中断的风险。Filebeat 能够读取并转发日志行,如果出现中断,还会在一切恢复正常后,从中断前停止的位置继续开始。 1.2.2 Filebeat 不会让通道过载 考虑到数据量较大,Filebeat 使用压力敏感协议向 Logstash 或 Elasticsearch 发送数据。如果 Logstash 正在繁忙地处理数据,它会告知 Filebeat 减慢读取速度。拥塞解决后,Filebeat 将恢复初始速度并继续输送数据。 1.2.3 不需要重载管道 当将数据发送到 Logstash 或 Elasticsearch 时,Filebeat 使用背压敏感协议,以考虑更多的数据量。如果 Logstash 正在忙于处理数据,则可以让 Filebeat 知道减慢读取速度。一旦拥堵得到解决,Filebeat 就会恢复到原来的步伐并继续运行。 1.2.4 输送至 Elasticsearch 或 Logstash。在 Kibana 中实现可视化。 Filebeat 是 Elastic Stack 的一部分,因此能够与 Logstash、Elasticsearch 和 Kibana 无缝协作。无论您要使用 Logstash 转换或充实日志和文件,还是在 Elasticsearch 中随意处理一些数据分析,亦或在 Kibana 中构建和分享仪表板,Filebeat 都能轻松地将您的数据发送至最关键的地方。 2. 性能 运行环境: OS 内存 CPU Filebeat版本 Logstash版本 CentOS 32g 6核Intel(R) Xeon(R) CPU E5-2620 v3 @ 2.40GHz 6.1 5.6.5 Logstash内存占用 [root@dde /]# cat /proc/20085/status /proc/20085/status | grep -i vm VmPeak: 9837428 kB VmSize: 9835376 kB VmLck: 0 kB VmHWM: 798364 kB VmRSS: 798360 kB VmData: 9677292 kB VmStk: 88 kB VmExe: 4 kB VmLib: 16520 kB VmPTE: 2568 kB VmSwap: 0 kB VmPeak: 9837428 kB VmSize: 9835376 kB VmLck: 0 kB VmHWM: 798364 kB VmRSS: 798360 kB VmData: 9677292 kB VmStk: 88 kB VmExe: 4 kB VmLib: 16520 kB VmPTE: 2568 kB VmSwap: 0 kB Filebeat内存占用 [root@dde /]# cat /proc/22207/status /proc/22207/status | grep -i vm VmPeak: 452796 kB VmSize: 410180 kB VmLck: 0 kB VmHWM: 16008 kB VmRSS: 16008 kB VmData: 376332 kB VmStk: 88 kB VmExe: 24764 kB VmLib: 1804 kB VmPTE: 184 kB VmSwap: 0 kB VmPeak: 452796 kB VmSize: 410180 kB VmLck: 0 kB VmHWM: 16008 kB VmRSS: 16008 kB VmData: 376332 kB VmStk: 88 kB VmExe: 24764 kB VmLib: 1804 kB VmPTE: 184 kB VmSwap: 0 kB Logstash因为是运行是JVM中的,可以看到Logstash内存占用比Filebeat大的多。 3. 安装 Filebeat官方提供了以下几种安装方式: (deb for Debian/Ubuntu, rpm for Redhat/Centos/Fedora, mac for OS X, docker for any Docker platform, and win for Windows). deb: curl -L -O https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-6.1.2-amd64.deb sudo dpkg -i filebeat-6.1.2-amd64.deb rpm: curl -L -O https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-6.1.2-x86_64.rpm sudo rpm -vi filebeat-6.1.2-x86_64.rpm mac curl -L -O https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-6.1.2-darwin-x86_64.tar.gz tar xzvf filebeat-6.1.2-darwin-x86_64.tar.gz docker: docker pull docker.elastic.co/beats/filebeat:6.1.2 windows: 1.下载zip包,地址。 2.解压到:C:\Program Files。 3.重命名文件夹为以下格式:filebeat-<version>-windows。 4.以管理员身份运行Shell。 5.使用如下命令,讲Filebeat安装为一个Windows Service: PS > cd 'C:\Program Files\Filebeat' PS C:\Program Files\Filebeat> .\install-service-filebeat.ps1 4. 配置 Elastic提供了一个配合ELK(Elasticsearch + Logstash + Kibana)的快速配置方式,不过我们不需要配合ELK使用Filebeat。直接配置filebeat根目录下filebeat.yml文件: filebeat.prospectors: - type: log enabled: true paths: - /var/log/*.log #- c:\programdata\elasticsearch\logs\* 需要配合elasticsearch使用时,增加以下配置: output.elasticsearch: hosts: ["192.168.1.42:9200"] 需要配合kibana使用时,增加以下配置: setup.kibana: host: "localhost:5601" Output Filebeat现在已经支持丰富的output类型: Elasticsearch Logstash Kafka Redis File Console Output codec Cloud output到kafka的配置类似: output.kafka: # initial brokers for reading cluster metadata hosts: ["kafka1:9092", "kafka2:9092", "kafka3:9092"] # message topic selection + partitioning topic: '%{[fields.log_topic]}' partition.round_robin: reachable_only: false required_acks: 1 compression: gzip max_message_bytes: 1000000 当事件的大小超过max_message_bytes的值的时候,会被直接丢弃不处理,所以要尽量控制filebeat产生的事件小于max_message_bytes的值。 上面示例中字段含义如下:enable: 该output是否生效;hosts:kafka broker集群地址;topic: kafka接收事件的topic;partition: kafka output的partioning 策略,可能值为:random, round_robin, hash。默认为hash;官方关于这几个可选值解释如下: random.group_events: Sets the number of events to be published to the same partition, before the partitioner selects a new partition by random. The default value is 1 meaning after each event a new partition is picked randomly. round_robin.group_events: Sets the number of events to be published to the same partition, before the partitioner selects the next partition. The default value is 1 meaning after each event the next partition will be selected. hash.hash: List of fields used to compute the partitioning hash value from. If no field is configured, the events key value will be used. hash.random: Randomly distribute events if no hash or key value can be computed. required_acks: kafka broker ACK可靠级别: 0=不需要响应, 1=等待本地commit, -1=等待所有的 replicascommit. 默认值为 1. Note: 如果设置为0,kafka将没有ACK返回,也许会有消息丢失或者错误。 5.运行 sudo ./filebeat -e -c filebeat.yml Filebeat目前已经支持Docker和Kubernetes。 5.1 Docker (1)pull image docker pull docker.elastic.co/beats/filebeat:6.1.2 (2) run image docker run \ -v ~/filebeat.yml:/usr/share/filebeat/filebeat.yml \ docker.elastic.co/beats/filebeat:6.1.2 (3) Configuration FROM docker.elastic.co/beats/filebeat:6.1.2 COPY filebeat.yml /usr/share/filebeat/filebeat.yml USER root RUN chown filebeat /usr/share/filebeat/filebeat.yml USER filebeat 5.2 Kubernetes (1)Deploy manifests curl -L -O https://raw.githubusercontent.com/elastic/beats/6.1/deploy/kubernetes/filebeat-kubernetes.yaml (2)Setting - name: ELASTICSEARCH_HOST value: elasticsearch - name: ELASTICSEARCH_PORT value: "9200" - name: ELASTICSEARCH_USERNAME value: elastic - name: ELASTICSEARCH_PASSWORD value: changeme (3)Deploy kubectl create -f filebeat-kubernetes.yaml check status $ kubectl --namespace=kube-system get ds/filebeat NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE NODE-SELECTOR AGE filebeat 32 32 0 32 0 <none> 1m 6. 参考资料 Elastic Filebeat Reference

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

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入门进阶课程8--Hive介绍和安装部署

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,博主为石山园,博客地址为http://www.cnblogs.com/shishanyuan。该系列课程是应邀实验楼整理编写的,这里需要赞一下实验楼提供了学习的新方式,可以边看博客边上机实验,课程地址为https://www.shiyanlou.com/courses/237 【注】该系列所使用到安装包、测试数据和代码均可在百度网盘下载,具体地址为http://pan.baidu.com/s/10PnDs,下载该PDF文件 1、搭建环境 部署节点操作系统为CentOS,防火墙和SElinux禁用,创建了一个shiyanlou用户并在系统根目录下创建/app目录,用于存放Hadoop等组件运行包。因为该目录用于安装hadoop等组件程序,用户对shiyanlou必须赋予rwx权限(一般做法是root用户在根目录下创建/app目录,并修改该目录拥有者为shiyanlou(chown–R shiyanlou:shiyanlou /app)。 Hadoop搭建环境: l虚拟机操作系统:CentOS6.664位,单核,1G内存 lJDK:1.7.0_55 64位 lHadoop:1.1.2 2、Hive介绍 Hive是Facebook开发的构建于Hadoop集群之上的数据仓库应用,它提供了类似于SQL语法的HQL语句作为数据访问接口,这使得普通分析人员的应用Hadoop的学习曲线变小,Hive有如下特性: lHive是基于Hadoop的一个数据仓库工具,可以将结构化的数据文件映射为一张数据库表,并使用sql语句转换为MapReduce任务进行运行。其优点是学习成本低,可以通过类SQL语句快速实现简单的MapReduce统计,不必开发专门的MapReduce应用,十分适合数据仓库的统计分析; lHive是建立在Hadoop上的数据仓库基础构架。它提供了一系列的工具,可以用来进行数据提取转化加载(ETL),这是一种可以存储、查询和分析存储在Hadoop中的大规模数据的机制。Hive定义了简单的类SQL查询语言,称为HQL,它允许熟悉SQL的用户查询数据。同时,这个语言也允许熟悉MapReduce开发者的开发自定义的Mapper和Reducer来处理内建的Mapper和Reducer无法完成的复杂的分析工作。 2.1Hive与关系数据库的区别 使用Hive的命令行接口很像操作关系数据库,但是Hive和关系数据库还是有很大的不同,Hive与关系数据库的区别具体如下: 1.Hive和关系数据库存储文件的系统不同,Hive使用的是Hadoop的HDFS(Hadoop的分布式文件系统),关系数据库则是服务器本地的文件系统; 2.Hive使用的计算模型是Mapreduce,而关系数据库则是自身的计算模型; 3.关系数据库都是为实时查询的业务进行设计的,而Hive则是为海量数据做数据挖掘设计的,实时性很差;实时性的区别导致Hive的应用场景和关系数据库有很大的不同; 4.Hive很容易扩展自己的存储能力和计算能力,这个是继承Hadoop的,而关系数据库在这个方面要比数据库差很多。 2.2Hive架构 由上图可知,Hadoop的mapreduce是Hive架构的根基。Hive架构包括如下组件:CLI(command line interface)、JDBC/ODBC、Thrift Server、WEB GUI、metastore和Driver(Complier、Optimizer和Executor),这些组件分为两大类:服务端组件和客户端组件。 服务端组件: lDriver组件:该组件包括Complier、Optimizer和Executor,它的作用是将HiveQL(类SQL)语句进行解析、编译优化,生成执行计划,然后调用底层的mapreduce计算框架; lMetastore组件:元数据服务组件,这个组件存储Hive的元数据,Hive的元数据存储在关系数据库里,Hive支持的关系数据库有derby和mysql。元数据对于Hive十分重要,因此Hive支持把metastore服务独立出来,安装到远程的服务器集群里,从而解耦Hive服务和metastore服务,保证Hive运行的健壮性; lThrift服务:thrift是facebook开发的一个软件框架,它用来进行可扩展且跨语言的服务的开发,Hive集成了该服务,能让不同的编程语言调用hive的接口。 客户端组件: lCLI:command line interface,命令行接口。 lThrift客户端:上面的架构图里没有写上Thrift客户端,但是Hive架构的许多客户端接口是建立在thrift客户端之上,包括JDBC和ODBC接口。 lWEBGUI:Hive客户端提供了一种通过网页的方式访问hive所提供的服务。这个接口对应Hive的hwi组件(hive web interface),使用前要启动hwi服务。 3、搭建Hive环境 3.1安装MySql数据库 3.1.1下载mysql安装文件 下载地址:http://dev.mysql.com/downloads/mysql/#downloads,使用系统为CentOS选择Red Hat Enterprise Linux/Oracle系列,也可以在/home/shiyanlou/install-pack目录中找到这些安装包: 操作系统为64位,选择对应安装包进行下载: 下载在本地目录如下图: 3.1.2安装mysql 使用命令查看是否已经安装过mysql: sudo rpm -qa | grep -i mysql 可以看到如下图的所示: 说明之前安装了mysql,可以参考4.1进行卸载旧的mysql。如果以前没有安装mysql则进入安装文件的目录,安装mysql服务端 cd /home/shiyanlou/install-pack sudo rpm -ivh MySQL-server-5.6.21-1.el6.x86_64.rpm 出现异常,通过分析缺少libaio依赖包,使用如下命令进行安装: sudo yum install libaio 再次安装mysql,并安装mysql客户端、mysql-devel sudo rpm -ivh MySQL-server-5.6.21-1.el6.x86_64.rpm sudo rpm -ivh MySQL-client-5.6.21-1.el6.x86_64.rpm sudo rpm -ivh MySQL-devel-5.6.21-1.el6.x86_64.rpm 3.1.3启动mysql服务 通过下面查看mysql服务状态: sudo service mysql status 如果mysql没有启动,通过如下命令进行启动: sudo service mysql start 3.1.4设置root密码 在CentOS6.5操作系统使用如下命令给mysql设置root密码时,出现如下错误: /usr/bin/mysqladmin -u root password 'root'; /usr/bin/mysqladmin: connect to server at 'localhost' failed error: 'Access denied for user 'root'@'localhost' (using password: NO)' 可以进入安全模式进行设置root密码 (1)停止mysql服务 使用如下命令停止mysql服务: sudo service mysql stop sudo service mysql status (2)跳过验证启动mysql 使用如下命令验证启动mysql,由于&结尾是后台运行进程,运行该命令可以再打开命令窗口或者Ctr+C继续进行下步操作: sudo mysqld_safe --skip-grant-tables & sudo service mysql status (3)跳过验证启动MySQL 验证mysql服务已经在后台运行后,执行如下语句,其中后面三条命令是在mysql语句: mysql -u root mysql>use mysql; mysql>update user set password = password('root') where user = 'root'; mysql>flush privileges; (4)跳过验证启动MySQL 重启mysql服务并查看状态 sudo service mysql restart sudo service mysql status 3.1.5设置Hive用户 进入mysql命令行,创建hive用户并赋予所有权限: mysql -uroot -proot mysql>set password=password('root'); mysql>create user 'hive' identified by 'hive'; mysql>grant all on *.* TO 'hive'@'%' identified by 'hive' with grant option; mysql>grant all on *.* TO 'hive'@'localhost' identified by 'hive' with grant option; mysql>flush privileges; (注意:如果是root第一次登录数据库,需要重新设置一下密码,所报异常信息如下:ERROR 1820 (HY000): You must SET PASSWORD before executing this statement) 3.1.6创建hive数据库 使用hive用户登录,创建hive数据库: mysql -uhive -phive -h hadoop mysql>create database hive; mysql>show databases; 3.2安装Hive 3.2.1解压并移动Hive安装包 可以到Apache基金hive官网http://hive.apache.org/downloads.html,选择镜像下载地址:http://mirrors.cnnic.cn/apache/hive/下载一个稳定版本,如下图所示: 也可以在/home/shiyanlou/install-pack目录中找到该安装包,解压该安装包并把该安装包复制到/app目录中 cd /home/shiyanlou/install-pack tar -xzf hive-0.12.0-bin.tar.gz mv hive-0.12.0-bin /app/hive-0.12.0 3.2.2解压并移动MySql驱动包 到mysql官网进入下载页面:http://dev.mysql.com/downloads/connector/j/,选择所需要的版本进行下载,这里下载的zip格式的文件 也可以在/home/shiyanlou/install-pack目录中找到该安装包,解压该安装包并把该安装包复制到/app/lib目录中 cd /home/shiyanlou/install-pack cp mysql-connector-java-5.1.22-bin.jar /app/hive-0.12.0/lib 3.2.3配置/etc/profile环境变量 使用如下命令打开/etc/profile文件: sudo vi /etc/profile 设置如下参数: export HIVE_HOME=/app/hive-0.12.0 export PATH=$PATH:$HIVE_HOME/bin export CLASSPATH=$CLASSPATH:$HIVE_HOME/bin 使配置文件生效: source /etc/profile echo $PATH 3.2.4设置hive-env.sh配置文件 进入hive-0.12.0/conf目录,复制hive-env.sh.templaete为hive-env.sh: cd /app/hive-0.12.0/conf cp hive-env.sh.template hive-env.sh sudo vi hive-env.sh 分别设置HADOOP_HOME和HIVE_CONF_DIR两个值: # Set HADOOP_HOME to point to a specific hadoop install directory export HADOOP_HOME=/app/hadoop-1.1.2 # Hive Configuration Directory can be controlled by: export HIVE_CONF_DIR=/app/hive-0.12.0/conf 3.2.5设置hive-site.xml配置文件 复制hive-default.xml.templaete为hive-site.xml cd /app/hive-0.12.0/conf cp hive-default.xml.template hive-site.xml sudo vi hive-site.xml (1)加入配置项 默认metastore在本地,添加配置改为非本地 <property> <name>hive.metastore.local</name> <value>false</value> </property> (2)修改配置项 hive默认为derby数据库,需要把相关信息调整为mysql数据库 <property> <name>hive.metastore.uris</name> <value>thrift://hadoop:9083</value> <description>Thrift URI for the remote metastore. ...</description> </property> <property> <name>javax.jdo.option.ConnectionURL</name> <value>jdbc:mysql://hadoop:3306/hive?=createDatabaseIfNotExist=true</value> <description>JDBC connect string for a JDBC metastore</description> </property> <property> <name>javax.jdo.option.ConnectionDriverName</name> <value>com.mysql.jdbc.Driver</value> <description>Driver class name for a JDBC metastore</description> </property> <property> <name>javax.jdo.option.ConnectionUserName</name> <value>hive</value> <description>username to use against metastore database</description> </property> <property> <name>javax.jdo.option.ConnectionPassword</name> <value>hive</value> <description>password to use against metastore database</description> </property> (3)订正错误项 在配置文件2000行左右配置项hive.server2.thrift.sasl.qop原来为<value>auth</auth>,按照如下进行修改: <property> <name>hive.server2.thrift.sasl.qop</name> <value>auth</value> <des..... </property> 并把hive.metastore.schema.verification配置项值修改为false <property> <name>hive.metastore.schema.verification</name> <value>false</value> <desc....> </property> 3.3验证部署 3.3.1启动metastore和hiveserver 在使用hive之前需要启动metastore和hiveserver服务,通过如下命令启用: hive --service metastore & hive --service hiveserver & 启动用通过jps命令可以看到两个进行运行在后台 3.3.2在hive中操作 登录hive,在hive创建表并查看该表,命令如下: hive hive>create table test(a string, b int); hive>show tables; hive>desc test; 登录mysql,在TBLS表中查看新增test表: mysql -uhive -phive mysql>use hive; mysql>select TBL_ID, CREATE_TIME, DB_ID, OWNER, TBL_NAME,TBL_TYPE from TBLS; 4、问题解决 4.1卸载旧的mysql (1)查找以前是否安装有mysql 使用命令查看是否已经安装过mysql: sudo rpm -qa | grep -i mysql 可以看到如下图的所示: 说明之前安装了: MySQL-client-5.6.21-1.el6.x86_64 MySQL-server-5.6.21-1.el6.x86_64 MySQL-devel-5.6.21-1.el6.x86_64 如果没有结果,可以进行跳到3.1.3步骤的mysql数据库安装 (2)停止mysql服务、删除之前安装的mysql 停止mysql服务、删除之前安装的mysql删除命令:rpm -ev–nodeps包名 sudo rpm -ev MySQL-server-5.6.21-1.el6.x86_64 sudo rpm -ev MySQL-devel-5.6.21-1.el6.x86_64 sudo rpm -ev MySQL-client-5.6.21-1.el6.x86_64 如果存在CentOS自带mysql-libs-5.6.21-1.el6.x86_64使用下面的命令卸载即可 sudo rpm -ev --nodeps mysql-libs-5.6.21-1.el6.x86_64 (3)查找之前老版本mysql的目录并且删除老版本mysql的文件和库 sudo find / -name mysql 删除对应的mysql目录 sudo rm -rf /usr/lib64/mysql sudo rm -rf /var/lib/mysql (4)再次查找机器是否安装mysql sudo rpm -qa | grep -i mysql 无结果,说明已经卸载彻底、接下来直接安装mysql即可 4.2Hive启动,报CommandNeedRetryException异常 启动hive时,出现CommandNeedRetryException异常,具体信息如下: Exception in thread "main" java.lang.NoClassDefFoundError:org/apache/hadoop/hive/ql/CommandNeedRetryException at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:270) at org.apache.hadoop.util.RunJar.main(RunJar.java:149) Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.hive.ql.CommandNeedRetryException at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) 由于以前使用hadoop时,修改hadoop-env.sh的HADOOP_CLASSPATH配置项,由以前的: export HADOOP_CLASSPATH=/app/hadoop-1.1.2/myclass 修改为: export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:/app/hadoop-1.1.2/myclass 4.3在Hive中使用操作语言 启动hive后,使用Hql出现异常,需要启动metastore和hiveserver FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.metastore.HiveMetaStoreClient 在使用hive之前需要启动metastore和hiveserver服务,通过如下命令启用: hive --service metastore & hive --service hiveserver & 启动用通过jps命令可以看到两个进行运行在后台 本文转自shishanyuan博客园博客,原文链接:http://www.cnblogs.com/shishanyuan/p/4648201.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,如需转载请自行联系原作者

资源下载

更多资源
腾讯云软件源

腾讯云软件源

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

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

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

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

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