因业务需要用到MD5,但Impala没有该函数,随借助UDF实现。以下是实现过程。
UDF实现要点:
- 根据集群中Hive的版本导入对应版本的hive-exec.jar
- 自定义UDF类要继承接口UDF
- 实现evaluate()方法
maven依赖:
<dependency> <groupId>org.apache.hive</groupId> <artifactId>hive-exec</artifactId> <version>1.1.0</version> </dependency>
源码:
import org.apache.hadoop.hive.ql.exec.UDF; import java.security.MessageDigest; public class MD5 extends UDF{ public static String evaluate(String value) { StringBuilder sb = new StringBuilder(); try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); byte[] bytes = messageDigest.digest(value.getBytes()); for (int i = 0; i < bytes.length; i++) { int tempInt = bytes[i] & 0xff; if (tempInt < 16) { sb.append(0); } sb.append(Integer.toHexString(tempInt)); } } catch (Exception e) { System.out.println(e.getMessage()); } return sb.toString(); } public static void main(String[] args) { String hello = "123456789"; System.out.println("MD5加密后的结果:" + evaluate(hello)); } }
导出jar包:mvn package
上传到Hdfs:hdfs dfs -copyFromLocal ./MyHiveUDF.jar /user/impala/user_function/
impala注册:在hue的impala查询界面(或者impala shell)中执行
create function md5(string) returns string location 'hdfs://nameservice/user/impala/user_function/MyHiveUDF.jar' symbol='com.business.bi.udf.MD5';
测试:
select MD5('123456789')
输出结果为 :25f9e794323b453885f5181f1b624d0b
上述过程执行完之后,在Hive中也可以使用该方法
参考:http://th7.cn/Program/java/201709/1257880.shtml