[01].平均值案例
AvgDemo
- 这里只贴出求身高平均值示例,其他的都一样。
项目源码和jar包请在主页连接中获取资源。
import java.io.IOException;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
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.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
public class AvgDemo {
public static void main(String[] args) throws IOException {
// 创建与数据库的连接
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", "192.168.109.123");
//conf.set("hbase.zookeeper.quorum", "master,slave1,slave2");
conf.set("hbase.zookeeper.property.clientPort", "2181");
Connection connection = ConnectionFactory.createConnection(conf);
// 定义要操作的表名
TableName tableName = TableName.valueOf("hadoop:student");
// 表相关的操作需要获取管理员对象,通过管理员对象操作表
Admin admin = connection.getAdmin();
// 检测指定的表是否存在
boolean isExists = admin.tableExists(tableName);
if (isExists) {
System.out.println("[表格存在]开始操作==========================================");
Table table = connection.getTable(tableName);
Scan scan = new Scan();
scan.addColumn("stu_info".getBytes(), "stature".getBytes());
//遍历单元格
int statureAll = 0;
int cellsNum = 0;
ResultScanner scanner = table.getScanner(scan);
for (Result result : scanner) {
List<Cell> cells = result.listCells();
cellsNum += cells.size();
for (Cell cell : cells) {
byte[] column_name = CellUtil.cloneQualifier(cell); // 该cell的列名
byte[] value = CellUtil.cloneValue(cell); // 该cell的值
String column = Bytes.toString(column_name);
if ("stature".equals(column)) {
Integer hight = Integer.parseInt(Bytes.toString(value));
statureAll += hight;
System.out.println("[学生身高]:"+hight);
}
}
}
System.out.println("[平均身高]:" + statureAll / cellsNum);
table.close(); // 关闭表
connection.close();// 关闭数据库
System.out.println("[操作完成]资源释放==========================================");
} else {
System.out.println("[表不存在]操作结束==========================================");
}
}
}
[02].打包运行效果
上传后使用命令:
java -jar avg_xxx.jar
身高
- 英语
- 数学
[03].如何打包?
- 首先让你的项目运行起来(不管报不报错),不然
Eclipse
不知道打包后的启动文件。 - 右键项目选择
Export
- 选择
Runnable JAR file
导出可运行jar包
- 第一个框框:项目主程序
- 第二个框框:导出的路径(自己填写)
- 第三:把所有jar资源全部导出,勾选第二个选项。