初探Google Guava

Guava地址:https://github.com/google/guavahtml

第一次接触我是在16年春github上,当时在找单机查缓存方法,google guava当初取名是由于JAVA的类库很差用,因此谷歌工程师本身开发一套,想着google出品必属精品理念,咱们一块儿来了解一下。java

guava在还没作分布式处理上,单机单整合上大行其道。因此guava在程序性能优化上下了很多的工夫,咱们称其为单块架构的利器git

我认为强大的有几点:1.集合处理   2.EventBus消息总线处理  3.guava cache 单机缓存处理  4.并发listenableFutrue回调处理,如下是全部的功能:github

1. 基本工具 [Basic utilities]

让使用Java语言变得更温馨web

1.1 使用和避免null:null是模棱两可的,会引发使人困惑的错误,有些时候它让人很不舒服。不少Guava工具类用快速失败拒绝null值,而不是盲目地接受spring

1.2 前置条件: 让方法中的条件检查更简单sql

1.3 常见Object方法: 简化Object方法实现,如hashCode()和toString()编程

1.4 排序: Guava强大的”流畅风格比较器”设计模式

1.5 Throwables:简化了异常和错误的传播与检查api

2. 集合[Collections]

Guava对JDK集合的扩展,这是Guava最成熟和为人所知的部分

2.1 不可变集合: 用不变的集合进行防护性编程和性能提高。

2.2 新集合类型: multisets, multimaps, tables, bidirectional maps等

2.3 强大的集合工具类: 提供java.util.Collections中没有的集合工具

2.4 扩展工具类:让实现和扩展集合类变得更容易,好比建立Collection的装饰器,或实现迭代器

3. 缓存[Caches]

Guava Cache:本地缓存实现,支持多种缓存过时策略

4. 函数式风格[Functional idioms]

Guava的函数式支持能够显著简化代码,但请谨慎使用它

5. 并发[Concurrency]

强大而简单的抽象,让编写正确的并发代码更简单

5.1 ListenableFuture:完成后触发回调的Future

5.2 Service框架:抽象可开启和关闭的服务,帮助你维护服务的状态逻辑

6. 字符串处理[Strings]

很是有用的字符串工具,包括分割、链接、填充等操做

7. 原生类型[Primitives]

扩展 JDK 未提供的原生类型(如int、char)操做, 包括某些类型的无符号形式

8. 区间[Ranges]

可比较类型的区间API,包括连续和离散类型

9. I/O

简化I/O尤为是I/O流和文件的操做,针对Java5和6版本

10. 散列[Hash]

提供比Object.hashCode()更复杂的散列实现,并提供布鲁姆过滤器的实现

11. 事件总线[EventBus]

发布-订阅模式的组件通讯,但组件不须要显式地注册到其余组件中

12. 数学运算[Math]

优化的、充分测试的数学工具类

13. 反射[Reflection]

Guava 的 Java 反射机制工具类

 

1.Guava EventBus探讨

在设计模式中, 有一种叫作发布/订阅模式, 即某事件被发布, 订阅该事件的角色将自动更新。
那么订阅者和发布者直接耦合, 也就是说在发布者内要通知订阅者说我这边有东西发布了, 你收一下。

Observable.just(1).subscribe(new Subsriber(){ @Override public void onCompleted() { System.out.println("onCompleted "); } @Override public void onError(Throwable arg0) { } @Override public void onNext(Long arg0) { System.out.println("onNext " + arg0); } }) 咱们能够看到, 发布者发布一个数字1, 订阅者订阅了这个 

而加入eventBus, 发布者与生产者之间的耦合性就下降了。由于这时候咱们去管理eventbus就能够, 发布者只要向eventbus发送信息就能够, 而不须要关心有多少订阅者订阅了此消息。模型以下

 

为何说eventBus 是单块架构的利器呢?

首先单块架构就是在一个进程内, 在一个进程内, 咱们仍是但愿模块与模块之间(功能与功能之间)是松耦合的,而在一个模块中是高度内聚的, 如何下降必定的耦合, 使得代码更加有结构, guava eventbus就是支持进程内通信的桥梁。

想象一下如下业务

咱们但愿在数据到来以后, 进行入库, 同时可以对数据进行报警预测, 当发生报警了, 可以有如下几个动做, 向手机端发送推送, 向web端发送推送, 向手机端发送短信。

在通常状况下咱们能够这样实现: (伪代码以下)

processData(data){
    insertintoDB(data); //执行入库操做
    predictWarning(data);   // 执行报警预测
}
在predictWarning(data)中{
    if(data reaches warning line){
        sendNotification2App(data); //向手机端发送推送
        sendNotification2Web(data); // 向web端发送推送
        sendSMS2APP(data);      //手机端发送短信
    }
}
在这里我不去讲具体是如何向web端发送推送, 如何发送短信。主要用到第三方平台

分析

入库和报警预测是没有直接联系,或者是不分前后顺序的, 一样在报警模块中, 向3个客户端发送信息也应该是没有联系的, 因此以上虽然能够实现功能, 但不符合代码的合理性。

应该是怎么样的逻辑呢? 以下图

 

 

当数据事件触发, 发布到data EventBus 上, 入库和预警分别订阅这个eventBus, 就会触发这两个事件, 而在预警事件中, 将事件发送到warning EventBus 中, 由下列3个订阅的客户端进行发送消息。

如何实现

先来说同步, 即订阅者收到事件后依次执行, 下面都是伪代码, 具体的入库细节等我在这里不提供。

@Component
public class DataHandler{
    
    @Subscribe
    public void handleDataPersisist(Data data){
        daoImpl.insertData2Mysql(data);
    }
    
    @Subscribe
    public void predictWarning(Data data){
        if(data is warning){ // pseudo code  若是预警
            Warning warning = createWarningEvent(data);  // 根据data建立一个Warning事件
            postWarningEvent(warning)
        }
    }
    
    protected postWarningEvent(Warning warning){
        EventBusManager.warningEventBus.post(warning);// 发布到warning event 上
    }
    
    @PostConstruct   // 由spring 在初始化bean后执行
    public void init(){
        register2DataEventBus();
    }
    
    // 将本身注册到eventBus中
    protected void register2DataEventBus(){
        EventBusManager.dataEventBus.register(this);
    }
    
}

@Component
public class WarningHandler{
    @Subscribe
    public void sendNotification2AppClient(Warning warning){
        JpushUtils.sendNotification(warning);
    }
    @Subscribe
    public void sendSMS(Warning warning){
        SMSUtils.sendSMS(warning);
    }
    @Subscribe
    public void send2WebUsingWebSocket(Warning warning){
        WebsocketUtils.sendWarning(warning);
    }
    
    @PostConstruct   // 由spring 在初始化bean后执行
    public void init(){
        register2WarningEventBus();
    }
    
    // 将本身注册到eventBus中
    protected void register2DataEventBus(){
        EventBusManager.warningEventBus.register(this);
    }
}


/**
 * 管理全部的eventBus
 **/
public class EventBusManager{
    public final static EventBus dataEventBus = new EventBus();
    public final static EventBus warningEventBus = new EventBus();
    
}



简化
// 咱们发现每个Handler都要进行注册,
public abstract class BaseEventBusHandler{
    
    @PostConstruct
    public void init(){
        register2EventBus();
    }
    private void register2EventBus(){
        getEventBus().register(this);
    }
    protected abstract EventBus getEventBus();
}
这样在写本身的eventBus只须要

@Component
public class MyEventBus extends BaseEventBusHandler{
    @Override
    protected abstract EventBus getEventBus(){
        retrun EventBusManager.myEventBus;
    }
}

在目前的应用场景下, 同步是咱们不但愿的, 异步场景也很容易实现。
只须要将EventBus 改为
 AsyncEventBus warningEvent = new AsyncEventBus(Executors.newFixedThreadPool(1))
 AsyncEventBus dataEventBus = new AsyncEventBus(Executors.newFixedThreadPool(3))

 

2.集合处理

1.optional空值比较

2.集合排序guava

Integer[] inumber={55,22,33};
        System.out.println(new Ordering<Integer>(){
            @Override
            public int compare(Integer left, Integer right) {
                return left-right;
            }
        }.sortedCopy(Arrays.asList(inumber)));

//java 须要自定义compare

 

3.guava cache 缓存触发机制

业务场景,当某一个文件保留的有效期30分钟后删除;某一个文件容易超过必定限定。

基于容量的回收:

规定缓存项的数目不超过固定值,只需使用CacheBuilder.maximumSize(long)。缓存将尝试回收最近没有使用或整体上不多使用的缓存项。—— 警告:在缓存项的数目达到限定值以前,即缓存项的数目逼近限定值时缓存就可能进行回收操做。这个size指的是cache中的条目数,不是内存大小或是其余.
public class GuavaCacheTest { public static void main(String[] args) { Cache<Integer, String> cache = CacheBuilder.newBuilder().maximumSize(2).build(); cache.put(1, "a"); cache.put(2, "b"); cache.put(3, "c"); System.out.println(cache.asMap()); System.out.println(cache.getIfPresent(2)); cache.put(4, "d"); System.out.println(cache.asMap()); } }

基于时间的回收

guava 提供两种定时回收的方法

expireAfterAccess(long, TimeUnit):缓存项在给定时间内没有被读/写访问,则回收。请注意这种缓存的回收顺序和基于大小回收同样。

expireAfterWrite(long, TimeUnit):缓存项在给定时间内没有被写访问(建立或覆盖),则回收。若是认为缓存数据老是在固定时候后变得陈旧不可用,这种回收方式是可取的。

public class GuavaCacheTest { public static void main(String[] args) { LoadingCache<Integer, Integer> cache = CacheBuilder.newBuilder().expireAfterWrite(3, TimeUnit.SECONDS).removalListener(new RemovalListener<Object, Object>() { @Override public void onRemoval(RemovalNotification<Object, Object> notification) { System.out.println("remove key[" + notification.getKey() + "],value[" + notification.getValue() + "],remove reason[" + notification.getCause() + "]"); } }).recordStats().build( new CacheLoader<Integer, Integer>() { @Override public Integer load(Integer key) throws Exception { return 2; } } ); cache.put(1, 1); cache.put(2, 2); System.out.println(cache.asMap()); cache.invalidateAll(); System.out.println(cache.asMap()); cache.put(3, 3); try { System.out.println(cache.getUnchecked(3)); Thread.sleep(4000); System.out.println(cache.getUnchecked(3)); } catch (InterruptedException e) { e.printStackTrace(); } } }

Cache<Integer, Integer> cache = CacheBuilder.newBuilder().maximumSize(100).expireAfterAccess(3, TimeUnit.SECONDS).build();

 4.ListenableFuture 异步回调通知

传统JDK中的Future经过异步的方式计算返回结果:在多线程运算中可能或者可能在没有结束返回结果,Future是运行中的多线程的一个引用句柄,确保在服务执行返回一个Result。

ListenableFuture能够容许你注册回调方法(callbacks),在运算(多线程执行)完成的时候进行调用,  或者在运算(多线程执行)完成后当即执行。这样简单的改进,使得能够明显的支持更多的操做,这样的功能在JDK concurrent中的Future是不支持的。

ListenableFuture 中的基础方法是addListener(Runnable, Executor), 该方法会在多线程运算完的时候,指定的Runnable参数传入的对象会被指定的Executor执行。

添加回调(Callbacks)

多数用户喜欢使用 Futures.addCallback(ListenableFuture<V>, FutureCallback<V>, Executor)的方式, 或者 另一个版本version(译者注:addCallback(ListenableFuture<V> future,FutureCallback<? super V> callback)),默认是采用 MoreExecutors.sameThreadExecutor()线程池, 为了简化使用,Callback采用轻量级的设计.  FutureCallback<V> 中实现了两个方法:

  • onSuccess(V),在Future成功的时候执行,根据Future结果来判断。
  • onFailure(Throwable), 在Future失败的时候执行,根据Future结果来判断。

ListenableFuture的建立

对应JDK中的 ExecutorService.submit(Callable) 提交多线程异步运算的方式,Guava 提供了ListeningExecutorService 接口, 该接口返回 ListenableFuture 而相应的 ExecutorService 返回普通的 Future。将 ExecutorService 转为 ListeningExecutorService,可使用MoreExecutors.listeningDecorator(ExecutorService)进行装饰。

ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)); ListenableFuture explosion = service.submit(new Callable() {
  public Explosion call() {
    return pushBigRedButton(); } }); Futures.addCallback(explosion, new FutureCallback() {
  // we want this handler to run immediately after we push the big red button!
  public void onSuccess(Explosion explosion) { walkAwayFrom(explosion); }
  public void onFailure(Throwable thrown) { battleArchNemesis(); // escaped the explosion! } });

 

 

原文出处:https://www.cnblogs.com/jay-wu/p/10244501.html

相关文章
相关标签/搜索