Java implements the server daemon to listen to clients write data to HBase by uploading JSON files

Source: Internet
Author: User

1. Project Introduction:

Since big data departments involve other departments transferring data to data centers, most companies use the same way as JSON files, so they need to write small programs for both the server and the client. And I mainly implement the service side of the code, there are corresponding to the client's test code. One of the needs to mention here is that while I am implementing the JSON file, I also need to write the data into HBase. Writing to HBase takes the form of bulk INSERT, where multiple records are inserted at one time.

Well, with the previous instructions, here is a brief description of my implementation of the service side of the small program.

2, in order to realize the service side can listen to the behavior of the client, so I use multi-threaded technology in the server to achieve, and the way to achieve network communication socket. The specific implementation is as follows:

Main programs on the server side:

Package Com.yiban.datacenter.finalversion;import Java.io.ioexception;import Java.net.serversocket;import Java.net.socket;public class Hbaseserver {public static void main (string[] args) {//TODO auto-generated method Stubbackpr Ocess ();} public static void Backprocess () {try {serversocket ss=new serversocket (11111), while (true) {Socket s=ss.accept (); Thread Deal=new Thread (new Dealuserthread (s));d Eal.setdaemon (true);  This sets the corresponding thread to be the background thread Deal.start ();}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

Thread class for processing data:

Here I implement the receive data and write the data to HBase.

While achieving these large targets, the client's request is also stored on the server's local disk in the form of a log file for subsequent viewing.

Package Com.yiban.datacenter.finalversion;import Java.io.bufferedreader;import Java.io.bufferedwriter;import Java.io.file;import Java.io.filewriter;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import Java.net.socket;import Java.text.simpledateformat;import java.util.ArrayList; Import Java.util.collection;import java.util.list;import Java.util.map;import Java.util.map.entry;import Java.util.set;import Java.util.treemap;import Net.sf.json.jsonarray;import Net.sf.json.jsonobject;import Org.apache.hadoop.conf.configuration;import Org.apache.hadoop.hbase.hbaseconfiguration;import Org.apache.hadoop.hbase.hcolumndescriptor;import Org.apache.hadoop.hbase.hconstants;import Org.apache.hadoop.hbase.htabledescriptor;import Org.apache.hadoop.hbase.masternotrunningexception;import Org.apache.hadoop.hbase.tablename;import Org.apache.hadoop.hbase.zookeeperconnectionexception;import Org.apache.hadoop.hbase.client.admin;import Org.apache.hadoop.hbase.clienT.connection;import Org.apache.hadoop.hbase.client.connectionfactory;import Org.apache.hadoop.hbase.client.hbaseadmin;import Org.apache.hadoop.hbase.client.htable;import Org.apache.hadoop.hbase.client.put;import Org.apache.hadoop.hbase.client.table;import Org.apache.hadoop.hbase.util.bytes;public class Dealuserthread implements Runnable {private String testconnect = " Username=chenpiao,password=123;username=liujiyu,password=123 "; This can be used to verify the user name and password private static Configuration conf = Hbaseconfiguration.create ();p rivate static Connection Connection = n Ull;private String logfile=null;//Configuring hbase information Static {try {Conf.set (hconstants.zookeeper_quorum, "192.168.27.233"); Conf.setint (Hconstants.zookeeper_client_port, 2181); connection = connectionfactory.createconnection (conf);} catch (Exception e) {//Todo:handle exceptione.printstacktrace ();}} Private socket S;public Dealuserthread (socket s) {THIS.S = s;} private string usertablename = "Nihao";p rivate string columnfamilyname = Null;private string ROwkey = null;private BufferedReader serverread = null;private BufferedWriter serverwrite = null; @Overridepublic void Run () {//TODO auto-generated method Stubtry {//Convert byte streams within the channel into character stream and encapsulate with BufferedReader. InputStreamReader is to convert byte streams to character stream serverread = new BufferedReader (New InputStreamReader (S.getinputstream ()));// Ask the client if the connection is ready, accept the connection request from the client string line = Serverread.readline (); Block//system.out.println (line);//Output Client connection request//Name the log file and create file SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd Hh:mm:ss "); Logfile= "/var/log/datacenter/" + "User.log";//system.out.println (LogFile); File DestFile = new file (logFile), if (!destfile.exists ()) {destfile.createnewfile ();} Writebyfilewrite (logFile, line+ "\ n" +sdf.format (System.currenttimemillis ()));//writes the characters in the channel to the corresponding file, Using Bufferedwrite for encapsulation, FileWriter writes a stream of characters to a file Serverwrite = new BufferedWriter (New OutputStreamWriter (S.getoutputstream ())); string[] Strarray = testconnect.split ("\ \;"); Boolean flag = False;for (String str:strarray) {if (Str.equals (line)) {/* * Serverwrite. Write ("The connection is successful, you can send the data, before sending the data, please send the database table name you want to use!") "); * Serverwrite.newline (); Serverwrite.flush (); */printinfomationforclient ("Connection successful, now can send data,befor send data, you must send tablename!"); flag = True;break;}} if (!flag) {/* * Serverwrite.write ("Password or username error, Connection failed! "); Serverwrite.newline (); * Serverwrite.flush (); */printinfomationforclient ("Username or password is error! Connection failed! "); S.close ();} Prepare to receive table name Usertablename = Serverread.readline ();//system.out.println ("tablename:" + usertablename);// The output client's connection request table name Writebyfilewrite (logFile, "tablename=" +usertablename);//writes the contents to the log file//tells the client that I accept the success if (Tableisexist ( Usertablename)) {printinfomationforclient ("received tablename successful!");} else {printinfomationforclient (" TableName is not exist "); S.close ();} line = "["; StringBuffer temp = new StringBuffer (line), while (line = Serverread.readline ())! = null) {temp.append (line);} Temp.append ("]");//system.out.println (temp.tostring ());//interface with the received data for exception handling, such as the uploaded data format is incorrect and so on. try {//to JSON textJsonarray Jsonarray = Jsonarray.fromobject (temp.tostring ());//Jsonobject Jsonobject=jsonobject.fromobject ( Temp.tostring ());//After parsing the output//printjsonarray (Jsonarray);//Get all the table names//getalltables (conf);// Writes the received data to a table in HBase insertdata (Jsonarray, usertablename);//system.out.println ("Deposit data successfully! ");} catch (Exception e) {printerrorforclient (e);} Give a feedback, indicating that the data upload success//package channel output stream, convenient for him to write character data//BufferedWriter Bwserver = new BufferedWriter (new//outputstreamwriter ( S.getoutputstream ()));/* * Serverwrite.write ("File upload successful!) "); Bwserver.newline (); * Serverwrite.flush (); Serverwrite.close (); */printinfomationforclient ("Upload data successful!"); /release Resources s.close ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace (); try {printerrorforclient (e); Writebyfilewrite (Logfile,e.getmessage () +e.tostring ());} catch (IOException E1) {//TODO auto-generated catch Blocke1.printstacktrace ();}}} private void Printinfomationforclient (String s) throws IOException {try {serverwrite.write (s); Writebyfilewrite (lOgfile, s);//writes the contents to the log file Serverwrite.newline (); Serverwrite.flush ();} catch (Exception e) {//Todo:handle exceptione.printstacktrace (); Writebyfilewrite (LogFile, E.getmessage () +e.tostring ());//writes the contents to the log file}}private void Printerrorforclient (Exception e) throws IOException {try {serverwrite.write ("found a Error: "+ e.getmessage () + e.tostring ()); Writebyfilewrite (LogFile," found a error: "+ e.getmessage () + e.tostring ()); Serverwrite.newline (); Serverwrite.flush (); S.close ();} catch (IOException E1) {//TODO auto-generated catch Blocke1.printstacktrace (); Writebyfilewrite (logfile,e1.getmessage () +e1.tostring ());}} map<string, string> colvalue = new treemap<string, string> ();p rivate void InsertData (Jsonarray JSONArray, String usertablename) throws IOException {//connect the tabletable table = null;try {table = connection.gettable (TableName . ValueOf (Usertablename));} catch (IOException E1) {//TODO auto-generated catch Blocke1.printstacktrace ();p rinterrorforclient (E1);} Colvalue.clear (); for (int i = 0; I < jsonarray.size (); i++) {Jsonobject obj = jsonarray.getjsonobject (i); set<string> keysets = Obj.keyset (); for (String key:keysets) {switch (key) {case "category": Columnfamilyname = obj. GetString (key); Break;case "version": Colvalue.put ("Version", Obj.getstring ("version"); Break;case "DocumentType": Colvalue.put ("DocumentType", Obj.getstring ("DocumentType")); Break;case "articles": Jsonarray articlesjars = Obj.getjsonarray ("articles");d Ealjsonarray (table,articlesjars); Break;default:printerrorforclient (New Exception ( "Send datatype is error!"));}}} private void insertcoldatatohbase (table table) throws IOException {//determines if the corresponding column family is included, if not included, adds Htabledescriptor desc = new Htab Ledescriptor (Table.getname ()); Collection

With this implementation, it is easy to deploy a jar package that is exported through Eclipse and put the jar package on the server for deployment, but also note that:

Java-jar Myserver.jar Com.yiban.datacenter.finalversion.HbaseServer &

The last & indicates that the daemon started the process.

Java implements the server daemon to listen to clients write data to HBase by uploading JSON files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.