Get rid of complicated Java tool classes, Hutool tool library is really fragrant~

Everyone is already familiar with Hutool. This is a super-complete Java tool library, which is deeply loved by domestic developers.

I actually didn't like to use such tools with too many functions before, and I was more worried about stability and security. After I slowly accepted it, I felt that it was actually okay. Moreover, we can also introduce only the functional modules we need, which is relatively flexible.

The official documentation of Hutool has already introduced it relatively clearly, but it provides too many functions. Here I list some functions that I personally think are more practical for your reference.

Hutool Introduction

Hutool is really a good domestic Java tool library with comprehensive functions. It encapsulates JDK methods such as files, streams, encryption and decryption, transcoding, regularization, threads, and XML, and works out of the box!

The official introduction of Hutool is as follows:

Hutool Introduction

The components included in Hutool and the functions provided by the components are shown in the table below:

Components included with Hutool

You can import each module individually according to project requirements, or you can hutool-allimport all modules by importing. However, it is not recommended to import all modules, because most of the functional items may not be used, it is recommended to only import the modules you need.

In addition, Hutool also has an obvious shortcoming. Many functions are relatively simple to implement, such as image verification codes and Excel tools, which may not meet the actual needs of the project. In such a situation, it is recommended that you choose a tool library that is better in a certain aspect, such as the Excel tool library MyExcel, EasyExcel, and the image processing library Imglib.

Hutool in action

Introduce dependencies

Maven warehouse address:

https://mvnrepository.com/artifact/cn.hutool 

Here, for convenience, we directly import all the modules. In actual projects, it is recommended to only import the modules you need.

Maven:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.16</version>
</dependency>

Gradle:

implementation 'cn.hutool:hutool-all:5.8.16'

Demo

Hutool provides too many functions, here are just some functions that I personally think are more practical, for your reference.

type conversion

Convert Classes encapsulate conversions to common Java types.

long[] b = {1,2,3,4,5};
String bStr = Convert.toStr(b);//"[1, 2, 3, 4, 5]"

double a = 67556.32;
String digitUppercase = Convert.digitToChinese(a);//"陆万柒仟伍佰伍拾陆元叁角贰分"

mail

Sending emails in Java mainly relies on  javax.mail packages, but because it is cumbersome to use, Hutool encapsulates them.

src/main/resourcesCreate a new file under the config directory of the classpath (in a standard Maven project ) mail.setting, and the complete configuration is as follows (the mail server must support and open the SMTP protocol):

# 邮件服务器的SMTP地址,可选,默认为smtp.<发件人邮箱后缀>
host = smtp.yeah.net
# 邮件服务器的SMTP端口,可选,默认25
port = 25
# 发件人(必须正确,否则发送失败)
from = [email protected]
# 用户名,默认为发件人邮箱前缀
user = hutool
# 密码(注意,某些邮箱需要为SMTP服务单独设置授权码,详情查看相关帮助)
pass = q1w2e3

Sending mail is very simple:

MailUtil.send("[email protected]", "测试", "邮件来自Hutool测试", false);

Support group sending:

ArrayList<String> tos = CollUtil.newArrayList(
    "[email protected]",
    "[email protected]",
    "[email protected]",
    "[email protected]");

MailUtil.send(tos, "测试", "邮件来自Hutool群发测试", false);

Support adding one or more attachments:

MailUtil.send("[email protected]", "测试", "<h1>邮件来自Hutool测试</h1>", true, FileUtil.file("d:/aaa.xml"));

In addition to using the configuration file to define the global account, MailUtil.sendthe method also provides an overloaded method to pass in an MailAccountobject, which is a common bean that records the mail server information.

MailAccount account = new MailAccount();
account.setHost("smtp.yeah.net");
account.setPort("25");
account.setAuth(true);
account.setFrom("[email protected]");
account.setUser("hutool");
account.setPass("q1w2e3");

MailUtil.send(account, CollUtil.newArrayList("[email protected]"), "测试", "邮件来自Hutool测试", false);

Unique ID

In a distributed environment, the unique ID generation is widely used, and the generation methods are also varied. Hutool makes a simple package for some common generation strategies.

The unique ID generator tool class provided by Hutool covers:

UUID

ObjectId(MongoDB)

Snowflake(Twitter)

Take UUID for example!

The logic rewritten by Hutool java.util.UUIDcorresponds to class cn.hutool.core.lang.UUID, so that the generation of UUID strings without - does not need to do character replacement, and the performance is improved by about one time .

//生成的UUID是带-的字符串,类似于:a5c8a5e8-df2b-4706-bea4-08d0939410e3
String uuid = IdUtil.randomUUID();

//生成的是不带-的字符串,类似于:b17f24ff026d40949c85a24f4f375d42
String simpleUUID = IdUtil.simpleUUID();

HTTP request tool class

For the most commonly used GET and POST requests, HttpUtil encapsulates two methods,

HttpUtil.get

HttpUtil.post

GET request:

// 最简单的HTTP请求,可以自动通过header等信息判断编码,不区分HTTP和HTTPS
String result1= HttpUtil.get("https://www.baidu.com");

// 当无法识别页面编码的时候,可以自定义请求页面的编码
String result2= HttpUtil.get("https://www.baidu.com", CharsetUtil.CHARSET_UTF_8);

//可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("city", "北京");

String result3= HttpUtil.get("https://www.baidu.com", paramMap);

POST request:

HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("city", "北京");

String result= HttpUtil.post("https://www.baidu.com", paramMap);

File Upload:

HashMap<String, Object> paramMap = new HashMap<>();
//文件上传只需将参数中的键指定(默认file),值设为文件对象即可,对于使用者来说,文件上传与普通表单提交并无区别
paramMap.put("file", FileUtil.file("D:\\face.jpg"));

String result= HttpUtil.post("https://www.baidu.com", paramMap);

cache

Hutool provides the implementation of several common caching strategies:

  1. FIFO(first in first out)  : First in first out policy.

  2. LFU(least frequently used)  : The least frequently used strategy.

  3. LRU(least recently used)  : The strategy has not been used for the longest time.

  4. Timed  : Timing strategy.

  5. Weak  : Weak reference strategy.

Moreover, Hutool also supports caching small files  byte[] into content in the form of , reducing file access, and solving performance problems caused by frequent file reading.

FIFO(first in first out) policy cache uses:

Cache<String,String> fifoCache = CacheUtil.newFIFOCache(3);

//加入元素,每个元素可以设置其过期时长,DateUnit.SECOND.getMillis()代表每秒对应的毫秒数,在此为3秒
fifoCache.put("key1", "value1", DateUnit.SECOND.getMillis() * 3);
fifoCache.put("key2", "value2", DateUnit.SECOND.getMillis() * 3);
fifoCache.put("key3", "value3", DateUnit.SECOND.getMillis() * 3);

//由于缓存容量只有3,当加入第四个元素的时候,根据FIFO规则,最先放入的对象将被移除
fifoCache.put("key4", "value4", DateUnit.SECOND.getMillis() * 3);

//value1为null
String value1 = fifoCache.get("key1");

Console print package

Under normal circumstances, we print information to the console, friends should be familiar with it!

System.out.println("Hello World");

However, this approach does not meet the needs of many scenarios:

1. Parameters are not supported, object printing needs to concatenate strings

2. The array cannot be printed directly, it needs to be called manuallyArrays.toString

For this purpose, Hutool encapsulates Consoleobjects.

ConsoleThe use of objects is more similar to console.log()the method of Javascript, which is also a syntactic sugar borrowed from JS.

String[] a = {"java", "c++", "c"};
Console.log(a);//控制台输出:[java, c++, c]

Console.log("This is Console log for {}.", "test");//控制台输出:This is Console log for test.

encrypt and decode

Hutool supports symmetric encryption, asymmetric encryption, digest encryption, message authentication code algorithm, and national secrets.

Here we take the national secret algorithm as an example. Hutool has Bouncy Castlemade a simplified package for implementing SM2, SM3, and SM4 in the national secret algorithm.

The National Secret Algorithm needs to introduce Bouncy Castlelibrary dependencies:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15to18</artifactId>
    <version>1.69</version>
</dependency>

SM2 encrypts or decrypts using a custom key pair  :

String text = "JavaGuide:一份涵盖大部分 Java 程序员所需要掌握的核心知识。准备 Java 面试,首选 JavaGuide!";
System.out.println("原文:" + text);

KeyPair pair = SecureUtil.generateKeyPair("SM2");
// 公钥
byte[] privateKey = pair.getPrivate().getEncoded();
// 私钥
byte[] publicKey = pair.getPublic().getEncoded();

SM2 sm2 = SmUtil.sm2(privateKey, publicKey);
// 公钥加密,私钥解密
String encryptStr = sm2.encryptBcd(text, KeyType.PublicKey);
System.out.println("加密后:" + encryptStr);

String decryptStr = StrUtil.utf8Str(sm2.decryptFromBcd(encryptStr, KeyType.PrivateKey));
System.out.println("解密后:" + decryptStr);

SM2 signature and verification  :

//加签
String sign = sm2.signHex(HexUtil.encodeHexStr(text));
System.out.println("签名:" + sign);
//验签
boolean verify = sm2.verifyHex(HexUtil.encodeHexStr(text), sign);
System.out.println("验签:" + verify);

Output result:

Thread Pool

Hutool supports using the builder pattern to create a custom thread pool, which makes it easier to see.

private static ExecutorService pool = ExecutorBuilder.create()
              .setCorePoolSize(10)//初始池大小
              .setMaxPoolSize(20) //最大池大小
              .setWorkQueue(new LinkedBlockingQueue<>(100))//最大等待数为100
              .setThreadFactory(ThreadFactoryBuilder.create().setNamePrefix("IM-Pool-").build())// 线程池命名
              .build();

In actual projects, if an object has many attributes, limited consideration should be given to using the builder pattern to create the object.

Moreover, Hutool also provides a global thread pool, and all asynchronous methods are executed in this thread pool by default.

ThreadUtil.execute : Execute threads directly in the public thread pool

ThreadUtil.execAsync: Execute an asynchronous method

......

Hutool itself is widely used  ThreadUtil, such as the sensitive word tool class  SensitiveUtil:

public static void init(final Collection<String> sensitiveWords, boolean isAsync){
  if(isAsync){
    // 异步初始化敏感词树
    ThreadUtil.execAsync(new Callable<Boolean>(){
      @Override
      public Boolean call() throws Exception {
        init(sensitiveWords);
        return true;
      }

    });
  }else{
    // 同步初始化敏感词树
    init(sensitiveWords);
  }
}

relevant address

  • project address:

    https://github.com/dromara/hutool

  • Official website:

    https://hutool.cn/

Guess you like

Origin blog.csdn.net/JACK_SUJAVA/article/details/130492925