您的位置 首页 > 德语词汇

guava是什么意思 介绍几个好用的guava工具类

各位老铁们好,相信很多人对guava是什么意思都不是特别的了解,因此呢,今天就来为大家分享下关于guava是什么意思以及介绍几个好用的guava工具类的问题知识,还望可以帮助大家,解决大家的一些困惑,下面一起来看看吧!

平时我们都会封装一些处理缓存或其他的小工具。但每个人都封装一次,重复造轮子,有点费时间。有没有一些好的工具库推荐-guava。guava是谷歌基于java封装好的开源库,它的性能、实用性,比我们自己造的轮子更好,毕竟谷歌出品,下面介绍下几个常用的guava工具类

guava是什么意思 介绍几个好用的guava工具类

<dependency>\n<groupId>com.google.guava</groupId>\n<artifactId>guava</artifactId>\n<version>27.0-jre</version>\n</dependency>\n复制代码LoadingCacheLoadingCache在实际场景中有着非常广泛的使用,通常情况下如果遇到需要大量时间计算或者缓存值的场景,就应当将值保存到缓存中。LoadingCache和ConcurrentMap类似,但又不尽相同。最大的不同是ConcurrentMap会永久的存储所有的元素值直到他们被显示的移除,但是LoadingCache会为了保持内存使用合理会根据配置自动将过期值移除通常情况下,Guavacaching适用于以下场景:花费一些内存来换取速度一些key会被不止一次被调用缓存内容有限,不会超过内存空间的值,Guavacaches不会存储内容到文件或者到服务器外部,如果有此类需求考虑使用Memcached,RedisLoadingCache不能缓存nullkeyCacheBuilder构造LoadingCache参数介绍

CacheBuilder方法参数

initialCapacity(intinitialCapacity)

concurrencyLevel(intconcurrencyLevel)

缓存池大小,在缓存项接近该大小时,Guava开始回收旧的缓存项

expireAfterWrite(longduration,TimeUnitunit)

设置时间对象没有被写则对象从内存中删除(在另外的线程里面不定期维护)

expireAfterAccess(longduration,TimeUnitunit)

设置时间对象没有被读/写访问则对象从内存中删除(在另外的线程里面不定期维护)

refreshAfterWrite(longduration,TimeUnitunit)

和expireAfterWrite类似,不过不立马移除key,而是在下次更新时刷新,这段时间可能会返回旧值

removalListener(RemovalListener<?superK1,?superV1>listener)

build(CacheLoader<?superK1,V1>loader)

当数据不存在时,则使用loader加载数据

LoadingCache<Integer,Long>cacheMap=CacheBuilder.newBuilder().initialCapacity(10)\n.concurrencyLevel(10)\n.expireAfterAccess(Duration.ofSeconds(10))\n.weakValues()\n.recordStats()\n.removalListener(newRemovalListener<Integer,Long>(){\n@Override\npublicvoidonRemoval(RemovalNotification<Integer,Long>notification){\nSystem.out.println(notification.getValue());\n}\n})\n.build(newCacheLoader<Integer,Long>(){\n@Override\npublicLongload(Integerkey)throwsException{\nreturnSystem.currentTimeMillis();\n}\n});\ncacheMap.get(1);\n复制代码Multimap和MultiSetMultimap的特点其实就是可以包含有几个重复Key的value,可以put进入多个不同value但是相同的key,但是又不会覆盖前面的内容示例

//Multimap:key-valuekey可以重复,value也可重复\nMultimap<String,String>multimap=ArrayListMultimap.create();\nmultimap.put("csc","1");\nmultimap.put("lwl","1");\nmultimap.put("csc","1");\nmultimap.put("lwl","one");\nSystem.out.println(multimap.get("csc"));\nSystem.out.println(multimap.get("lwl"));\n---------------------------\n[1,1]\n[1,one]\n复制代码MultiSet有一个相对有用的场景,就是跟踪每种对象的数量,所以可以用来进行数量统计示例

//MultiSet:无序+可重复count()方法获取单词的次数增强了可读性+操作简单\nMultiset<String>set=HashMultiset.create();\nset.add("csc");\nset.add("lwl");\nset.add("csc");\nSystem.out.println(set.size());\nSystem.out.println(set.count("csc"));\n---------------------------\n3\n2\n复制代码BiMapBiMap的键必须唯一,值也必须唯一,可以实现value和key互转示例

BiMap<Integer,String>biMap=HashBiMap.create();\nbiMap.put(1,"lwl");\nbiMap.put(2,"csc");\nBiMap<String,Integer>map=biMap.inverse();//value和key互转\nmap.forEach((v,k)->System.out.println(v+"-"+k));\n复制代码TableTable<R,C,V>table=HashBasedTable.create();,由泛型可以看出,table由双主键R(行),C(列)共同决定,V是存储值新增数据:table.put(R,C,V)获取数据:Vv=table.get(R,C)遍历数据:Set<R>set=table.rowKeySet();Set<C>set=table.columnKeySet();示例

//双键的MapMap-->Table-->rowKey+columnKey+value\nTable<String,String,Integer>tables=HashBasedTable.create();\ntables.put("csc","lwl",1);\n//row+column对应的value\nSystem.out.println(tables.get("csc","lwl"));\n复制代码Sets和Maps

//不可变集合的创建\nImmutableList<String>iList=ImmutableList.of("csc","lwl");\nImmutableSet<String>iSet=ImmutableSet.of("csc","lwl");\nImmutableMap<String,String>iMap=ImmutableMap.of("csc","hello","lwl","world");\n复制代码set的交集,并集,差集

HashSetsetA=newHashSet(1,2,3,4,5);\nHashSetsetB=newHashSet(4,5,6,7,8);\n//并集\nSetViewunion=Sets.union(setA,setB);\n//差集setA-setB\nSetViewdifference=Sets.difference(setA,setB);\n//交集\nSetViewintersection=Sets.intersection(setA,setB);\n复制代码map的交集,并集,差集

HashMap<String,Integer>mapA=Maps.newHashMap();\nmapA.put("a",1);mapA.put("b",2);mapA.put("c",3);\nHashMap<String,Integer>mapB=Maps.newHashMap();\nmapB.put("b",20);mapB.put("c",3);mapB.put("d",4);\nMapDifference<String,Integer>mapDifference=Maps.difference(mapA,mapB);\n//mapA和mapB相同的entry\nSystem.out.println(mapDifference.entriesInCommon());\n//mapA和mapBkey相同的value不同的entry\nSystem.out.println(mapDifference.entriesDiffering());\n//只存在mapA的entry\nSystem.out.println(mapDifference.entriesOnlyOnLeft());\n//只存在mapB的entry\nSystem.out.println(mapDifference.entriesOnlyOnRight());;\n-------------结果-------------\n{c=3}\n{b=(2,20)}\n{a=1}\n{d=4}\n复制代码EventBusEventBus是Guava的事件处理机制,是设计模式中的观察者模式(生产/消费者编程模型)的优雅实现。对于事件监听和发布订阅模式EventBus内部实现原理不复杂,EventBus内部会维护一个Multimap<Class<?>,Subscriber>map,key就代表消息对应的类(不同消息不同类,区分不同的消息)、value是一个Subscriber,Subscriber其实就是对应消息处理者。如果有消息发布就去这个map里面找到这个消息对应的Subscriber去执行使用示例

@Data\n@AllArgsConstructor\npublicclassOrderMessage{\nStringmessage;\n}\n//使用@Subscribe注解,表明使用dealWithEvent方法处理OrderMessage类型对应的消息\n//可以注解多个方法,不同的方法处理不同的对象消息\npublicclassOrderEventListener{\n@Subscribe\npublicvoiddealWithEvent(OrderMessageevent){\nSystem.out.println("内容:"+event.getMessage());\n}\n}\n-------------------------------------\n//newAsyncEventBus(Stringidentifier,Executorexecutor);\nEventBuseventBus=newEventBus("lwl");\neventBus.register(newOrderEventListener());\n//发布消息\neventBus.post(newOrderMessage("csc"));\n复制代码StopWatch

Stopwatchstopwatch=Stopwatch.createStarted();\nfor(inti=0;i<100000;i++){\n//dosomething\n}\nlongnanos=stopwatch.elapsed(TimeUnit.MILLISECONDS);\nSystem.out.println("逻辑代码运行耗时:"+nanos);\n复制代码Files文件操作数据写入

FilenewFile=newFile("D:/text.txt");\nFiles.write("thisisatest".getBytes(),newFile);\n//再次写入会把之前的内容冲掉\nFiles.write("csc".getBytes(),newFile);\n//追加写\nFiles.append("lwl",newFile,Charset.defaultCharset());\n复制代码文本数据读取

FilenewFile=newFile("E:/text.txt");\nList<String>lines=Files.readLines(newFile,Charset.defaultCharset());\n复制代码其他操作

方法

Files.deleteDirectoryContents(Filedirectory)

删除文件夹下的内容(包括文件与子文件夹)

Files.deleteRecursively(Filefile)

Files.getFileExtension(Stringfile)

Files.getNameWithoutExtension(Stringfile)

Files.map(Filefile,MapModemode)

//RateLimiter构造方法,每秒限流permitsPerSecond\npublicstaticRateLimitercreate(doublepermitsPerSecond)\n//每秒限流permitsPerSecond,warmupPeriod则是数据初始预热时间,从第一次acquire或tryAcquire执行开时计算\npublicstaticRateLimitercreate(doublepermitsPerSecond,DurationwarmupPeriod)\n//获取一个令牌,阻塞,返回阻塞时间\npublicdoubleacquire()\n//获取permits个令牌,阻塞,返回阻塞时间\npublicdoubleacquire(intpermits)\n//获取一个令牌,超时返回\npublicbooleantryAcquire(Durationtimeout)\n////获取permits个令牌,超时返回\npublicbooleantryAcquire(intpermits,Durationtimeout)\n复制代码使用示例

RateLimiterlimiter=RateLimiter.create(2,3,TimeUnit.SECONDS);\nSystem.out.println("getonepermitcosttime:"+limiter.acquire(1)+"s");\nSystem.out.println("getonepermitcosttime:"+limiter.acquire(1)+"s");\nSystem.out.println("getonepermitcosttime:"+limiter.acquire(1)+"s");\nSystem.out.println("getonepermitcosttime:"+limiter.acquire(1)+"s");\nSystem.out.println("getonepermitcosttime:"+limiter.acquire(1)+"s");\nSystem.out.println("getonepermitcosttime:"+limiter.acquire(1)+"s");\nSystem.out.println("getonepermitcosttime:"+limiter.acquire(1)+"s");\nSystem.out.println("getonepermitcosttime:"+limiter.acquire(1)+"s");\n---------------结果-------------------------\ngetonepermitcosttime:0.0s\ngetonepermitcosttime:1.331672s\ngetonepermitcosttime:0.998392s\ngetonepermitcosttime:0.666014s\ngetonepermitcosttime:0.498514s\ngetonepermitcosttime:0.498918s\ngetonepermitcosttime:0.499151s\ngetonepermitcosttime:0.488548s\n复制代码因为RateLimiter滞后处理的,所以第一次无论取多少都是零秒可以看到前四次的acquire,花了三秒时间去预热数据,在第五次到第八次的acquire耗时趋于平滑GuavaRetrymaven引入

<dependency>\n<groupId>com.github.rholder</groupId>\n<artifactId>guava-retrying</artifactId>\n<version>2.0.0</version>\n</dependency>\n复制代码RetryerBuilder构造方法

RetryerBuilder方法

发生RuntimeException异常,则重试

retryIfExceptionOfType(Class<?extendsThrowable>ex)

retryIfException(Predicate<Throwable>exceptionPredicate)

retryIfResult(Predicate<V>resultPredicate)

Retryer<Boolean>retryer=RetryerBuilder.<Boolean>newBuilder()\n.retryIfException()\n.retryIfResult(Predicates.equalTo(false))\n.withAttemptTimeLimiter(AttemptTimeLimiters.fixedTimeLimit(1,TimeUnit.SECONDS))\n.withStopStrategy(StopStrategies.stopAfterAttempt(5))\n.build();\n//Retryer调用\nretryer.call(()->true);\n复制代码spring也有对应的重试机制,相关文章可以看看重试框架Guava-Retry和spring-Retry

作者:潜行前行链接:https://juejin.cn/post/6974202216768864264来源:掘金著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

关于guava是什么意思到此分享完毕,希望能帮助到您。

本站涵盖的内容、图片、视频等数据,部分未能与原作者取得联系。若涉及版权问题,请及时通知我们并提供相关证明材料,我们将及时予以删除!谢谢大家的理解与支持!

Copyright © 2023