CommonHBaseService.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. package com.primeton.dsp.datarelease.data.service;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.google.common.cache.Cache;
  4. import com.google.common.cache.CacheBuilder;
  5. import com.google.common.cache.RemovalListener;
  6. import com.google.common.cache.RemovalNotification;
  7. import org.apache.commons.lang.StringUtils;
  8. import org.apache.hadoop.conf.Configuration;
  9. import org.apache.hadoop.hbase.HBaseConfiguration;
  10. import org.apache.hadoop.hbase.TableName;
  11. import org.apache.hadoop.hbase.client.*;
  12. import org.apache.hadoop.hbase.util.Bytes;
  13. import org.slf4j.Logger;
  14. import org.slf4j.LoggerFactory;
  15. import java.io.Closeable;
  16. import java.io.IOException;
  17. import java.util.*;
  18. import java.util.concurrent.TimeUnit;
  19. /**
  20. * <p>
  21. * HBase 操作类工具类。
  22. * </p>
  23. * <p/>
  24. * Created by ZhenQin on 2018/5/17 0017-9:52
  25. * Vendor: 9sdata.cn
  26. */
  27. public class CommonHBaseService implements Closeable {
  28. /**
  29. * 对象值转为 Byte[] 类型,先转为 文本类型再转为 byte[]
  30. */
  31. public final static int TEXT_BYTES_TYPE = 0;
  32. /**
  33. * HBase key 和 value 全部为 bin 类型
  34. */
  35. public final static int BIN_BYTES_TYPE = 1;
  36. /**
  37. * Hbase table cached
  38. */
  39. final static Cache<String, Table> HBASE_TABLE_CACHED = CacheBuilder.newBuilder()
  40. .maximumSize(100)
  41. .initialCapacity(20)
  42. .expireAfterAccess(30, TimeUnit.MINUTES) // 30 分钟不从缓存中读取该表,则移除出缓存
  43. .removalListener(new RemovalListener<String, Table>() {
  44. @Override
  45. public void onRemoval(RemovalNotification<String, Table> notification) {
  46. try {
  47. notification.getValue().close();
  48. } catch (IOException e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. })
  53. .build();
  54. /**
  55. * tablename
  56. */
  57. final String tableName;
  58. /**
  59. * Hbase Table
  60. */
  61. final Table table;
  62. /**
  63. * 选择
  64. */
  65. private int bytesType = TEXT_BYTES_TYPE;
  66. final static Logger logger = LoggerFactory.getLogger(CommonHBaseService.class);
  67. /**
  68. * 构造方法传入Hbase Table
  69. *
  70. * @param table
  71. */
  72. public CommonHBaseService(Table table) {
  73. this(table, TEXT_BYTES_TYPE);
  74. }
  75. /**
  76. * 构造方法传入Hbase Table
  77. *
  78. * @param table
  79. */
  80. public CommonHBaseService(Table table, int type) {
  81. this.table = table;
  82. this.tableName = table.getName().getNameAsString();
  83. this.bytesType = type;
  84. }
  85. public CommonHBaseService(Connection connection, String tableName) throws IOException {
  86. Table table = HBASE_TABLE_CACHED.getIfPresent(tableName);
  87. if (table == null) {
  88. boolean existsTable = connection.getAdmin().tableExists(TableName.valueOf(tableName));
  89. //boolean existsTable = false;
  90. if (!existsTable) {
  91. logger.warn("table: " + tableName + " not exists.");
  92. this.tableName = null;
  93. //throw new IllegalStateException("table: " + tableName + " not exists.");
  94. this.table = null;
  95. } else {
  96. this.tableName = tableName;
  97. this.table = connection.getTable(TableName.valueOf(tableName));
  98. HBASE_TABLE_CACHED.put(tableName, this.table);
  99. }
  100. } else {
  101. this.tableName = tableName;
  102. this.table = table;
  103. }
  104. this.bytesType = TEXT_BYTES_TYPE;
  105. }
  106. public CommonHBaseService(Configuration conf, String tableName) throws IOException {
  107. this(ConnectionFactory.createConnection(conf), tableName);
  108. }
  109. public int put(JSONObject values, String defaultFamily) throws IOException {
  110. String key = values.getString("key");
  111. final JSONObject copy = new JSONObject(values.size() - 1);
  112. Set<Map.Entry<String, Object>> entries = values.entrySet();
  113. for (Map.Entry<String, Object> entry : entries) {
  114. if ("key".equals(entry.getKey())) {
  115. continue;
  116. }
  117. copy.put(entry.getKey(), entry.getValue());
  118. }
  119. return put(key, copy, defaultFamily);
  120. }
  121. public int put(String key, JSONObject values, String defaultFamily) throws IOException {
  122. table.put(jsonConvert2Put(key, values, defaultFamily));
  123. return 1;
  124. }
  125. public int puts(JSONObject[] values, String defaultFamily) throws IOException {
  126. return puts(Arrays.asList(values), defaultFamily);
  127. }
  128. public int puts(Collection<JSONObject> values, String defaultFamily) throws IOException {
  129. List<Put> puts = new ArrayList<>(values.size());
  130. for (JSONObject value : values) {
  131. puts.add(jsonConvert2Put(value.getString("key"), value, defaultFamily));
  132. }
  133. table.put(puts);
  134. return puts.size();
  135. }
  136. /**
  137. * 把 JSON 转为 HBase 的 put, json 中一定要包含 key 字段
  138. *
  139. * @param key
  140. * @param value
  141. * @param defaultFamily
  142. * @return
  143. */
  144. private Put jsonConvert2Put(String key, JSONObject value, String defaultFamily) {
  145. if (StringUtils.isBlank(key)) {
  146. throw new IllegalArgumentException("no key value to set...");
  147. }
  148. Put put = new Put(Bytes.toBytes(key));
  149. Set<Map.Entry<String, Object>> entries = value.entrySet();
  150. for (Map.Entry<String, Object> entry : entries) {
  151. String field = entry.getKey();
  152. if (StringUtils.isBlank(field) || ":".equals(field)) {
  153. throw new IllegalArgumentException("invalid field: " + field);
  154. }
  155. int indexOf = field.indexOf(":");
  156. if (indexOf <= 0) {
  157. //a=abc OR :a=abc
  158. field = indexOf == 0 ? field.substring(1) : field;
  159. put.addColumn(Bytes.toBytes(defaultFamily), Bytes.toBytes(field), getBytes(entry.getValue()));
  160. } else {
  161. //f:a=abc
  162. String f = field.substring(0, indexOf);
  163. String x = field.substring(indexOf + 1);
  164. put.addColumn(Bytes.toBytes(f), Bytes.toBytes(x), getBytes(entry.getValue()));
  165. }
  166. }
  167. return put;
  168. }
  169. /**
  170. * 对象值转为 byte[] 类型
  171. *
  172. * @param value
  173. * @return
  174. */
  175. private byte[] getBytes(Object value) {
  176. if (value == null) {
  177. return new byte[0];
  178. }
  179. if (value instanceof String) {
  180. return Bytes.toBytes((String) value);
  181. }
  182. if (value instanceof byte[]) {
  183. return (byte[]) value;
  184. }
  185. if (bytesType == 0) {
  186. return Bytes.toBytes(String.valueOf(value));
  187. }
  188. if (value instanceof Integer) {
  189. return Bytes.toBytes((Integer) value);
  190. } else if (value instanceof Long) {
  191. return Bytes.toBytes((Long) value);
  192. } else if (value instanceof Double) {
  193. return Bytes.toBytes((Double) value);
  194. } else if (value instanceof Float) {
  195. return Bytes.toBytes((Float) value);
  196. } else if (value instanceof Byte) {
  197. return Bytes.toBytes((Byte) value);
  198. } else if (value instanceof Boolean) {
  199. return Bytes.toBytes((Boolean) value);
  200. } else if (value instanceof Short) {
  201. return Bytes.toBytes((Short) value);
  202. } else if (value instanceof Date) {
  203. return Bytes.toBytes(((Date) value).getTime());
  204. }
  205. // 其他的未知类型,统一设置为字符串
  206. return Bytes.toBytes(String.valueOf(value));
  207. }
  208. /**
  209. * HBaseResult 转换为JSON, HBase rowkey 放在 json的 row 里,必须是字符串形式。
  210. *
  211. * @param result
  212. * @return
  213. */
  214. private JSONObject result2JSON(Result result) {
  215. JSONObject json = new JSONObject();
  216. byte[] row = result.getRow();
  217. if (row == null || row.length == 0) {
  218. return json;
  219. }
  220. json.put("key", Bytes.toString(row));
  221. NavigableMap<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> map = result.getMap();
  222. if (map == null || map.isEmpty()) {
  223. return json;
  224. }
  225. for (Map.Entry<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> entry : map.entrySet()) {
  226. byte[] familyBytes = entry.getKey();
  227. String family = Bytes.toString(familyBytes);
  228. NavigableMap<byte[], NavigableMap<Long, byte[]>> values = entry.getValue();
  229. for (Map.Entry<byte[], NavigableMap<Long, byte[]>> en : values.entrySet()) {
  230. String field = Bytes.toString(en.getKey());
  231. NavigableMap<Long, byte[]> value = en.getValue();
  232. Map.Entry<Long, byte[]> firstEntry = value.firstEntry();
  233. if (firstEntry != null) {
  234. json.put(family + ":" + field, Bytes.toString(firstEntry.getValue()));
  235. }
  236. }
  237. }
  238. return json;
  239. }
  240. public JSONObject get(String rowKey) throws IOException {
  241. if (StringUtils.isBlank(this.tableName)) {
  242. // table not exists.
  243. return null;
  244. }
  245. Result result = table.get(new Get(Bytes.toBytes(rowKey)));
  246. if (result == null) {
  247. return null;
  248. }
  249. return result2JSON(result);
  250. }
  251. public List<JSONObject> get(List<String> rowKeys) throws IOException {
  252. if (StringUtils.isBlank(this.tableName)) {
  253. // table not exists.
  254. return null;
  255. }
  256. List<Get> gets = new ArrayList<>(rowKeys.size());
  257. for (String rowKey : rowKeys) {
  258. gets.add(new Get(Bytes.toBytes(rowKey)));
  259. }
  260. Result[] results = table.get(gets);
  261. if (results == null) {
  262. return null;
  263. }
  264. List<JSONObject> res = new ArrayList<>(rowKeys.size());
  265. for (Result result : results) {
  266. res.add(result2JSON(result));
  267. }
  268. return res;
  269. }
  270. public int delete(String rowkey) throws IOException {
  271. table.delete(new Delete(Bytes.toBytes(rowkey)));
  272. return 1;
  273. }
  274. public int delete(byte[] rowkey) throws IOException {
  275. table.delete(new Delete(rowkey));
  276. return 1;
  277. }
  278. public int delete(String... rowkeys) throws IOException {
  279. return delete(Arrays.asList(rowkeys));
  280. }
  281. public int delete(Collection<String> rowkeys) throws IOException {
  282. List<Delete> deletes = new ArrayList<>(rowkeys.size());
  283. for (String rowkey : rowkeys) {
  284. deletes.add(new Delete(Bytes.toBytes(rowkey)));
  285. }
  286. table.delete(deletes);
  287. return deletes.size();
  288. }
  289. @Override
  290. public void close() throws IOException {
  291. if(table != null) {
  292. table.close();
  293. }
  294. }
  295. public void setBytesType(int bytesType) {
  296. this.bytesType = bytesType;
  297. }
  298. }