guava学习笔记

1.CaseFormat

CaseFormat是guava中用于字符串格式转换的工具有以下几种类型

UPPER_CAMEL,比如 UpperCamel

UPPER_UNDERSCORE,比如 UPPER_UNDERSCORE

LOWER_CAMEL,比如 lowerCamel

LOWER_HYPHEN,比如 lower-hyphen

LOWER_UNDERSCORE,比如 lower_underscore

 

可以使用to进行转换

// 从大写驼峰转小写驼峰
System.out.println(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, "UpperCamel"));

也可以使用converter进行转换

Converter<String, String> converter = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
System.out.println(converter.convert("UpperCamel"));

2.guava cache

guava cache是一种非常优秀本地缓存解决方案,提供了基于容量,时间和引用的缓存回收方式

guava cache作为本地缓存,对于redis,redis将会受到网卡等原因,所以缓存的方案可以是DB+redis+local cache

使用的场景:

1.愿意消耗一些内存空间来提升速度
2.预料到某些键会被多次查询
3.缓存中存放的数据总量不会超出内存容量

参考:https://www.jianshu.com/p/38bd5f1cf2f2

其他的本地缓存方案还有:caffeine

3.Preconditions

可以使用Preconditions来优雅的进行参数的校验,比如

Preconditions.checkNotNull(jedisPoolConfig, "Redis pool config should not be Null");
Preconditions.checkArgument(minIdle >= 0, "minIdle value can not be negative");

4.Hash

可以使用guava来对进行哈希

下面的例子使用了md5,还有其他的哈希方法,比如murmur3(es使用的路由哈希算法),sha256,crc32等

HashCode hash = Hashing.md5().hashString("123456"); // 等同于Hashing.md5().hashString("123456", Charsets.UTF_16LE);
System.out.println(hash.toString());

HashCode hash2 = Hashing.md5().hashString("123456", StandardCharsets.UTF_8); // 等同于Hashing.md5().hashBytes("123456".getBytes()).toString()
System.out.println(hash2.toString());

分别输出

ce0bfd15059b68d67688884d7a3d3e8c
e10adc3949ba59abbe56e057f20f883e

在Linux上使用md5sum,等同于使用 Hashing.md5().hashString("123456", StandardCharsets.UTF_8)

echo -n '123456' | md5sum
e10adc3949ba59abbe56e057f20f883e  -

5.EventBus

EventBus是guava提供的一种消息发布-订阅类库

参考:Guava-EventBus使用详解

6.RateLimiter

RateLimiter limiter = RateLimiter.create(1.0); // 这里的1表示每秒允许处理的量为1个
for (int i = 1; i <= 10; i++) { 
    limiter.acquire();// 请求RateLimiter, 超过permits会被阻塞
    System.out.println("call execute.." + i);
}

参考:Guava RateLimiter实现接口API限流

7.去掉字符串的空格和换行

CharMatcher.breakingWhitespace().removeFrom(str)

  

 

posted @ 2020-07-25 22:58  tonglin0325  阅读(374)  评论(0编辑  收藏  举报