文章转载自IOT School:https://www.iotschool.com/
预备知识
方法引用的唯一用途是支持 Lambda 表达式的简写,调用方法的时候使用::, 对于一些单个参数,可以自动推断;
- Consumer
Consumer的作用是给定义一个参数,对其进行 (消费) 处理,处理的方式可以是任意操作,无返回值;
- Predicate
断言接口,根据传入的 Lambda 表达式返回 boolean;
- Supplier
根据提供的 Lambda 表达式返回需要的对象;
- Function
函数式编程接口,根据提供的 Lambda 表达式进行相应的操作并返回结果;
注解
@postConstruct 注解并非为 spring 提供, 该注解用来修饰非静态void()方法,该注解的执行时机为在对象加载完依赖注入后执行,即Constructor > @Autowired > @postConstruct;
由 spring 提供,spring 为我们提供了事件的监听与实现,内部的实现原理是观察者设计模式,实现了系统解耦,时间发布者不需要考虑谁在监听,发布者只关心自己消息的发布;
- ApplicationReadyEvent
应用已经就绪处理请求,将会发布该事件;(AnApplicationReadyEventis sent after any application and command-line runners have been called. It indicates that the application is ready to service requests.)- _@_Conditional及包括其子注解
spring 提供,对满足条件进行注入;
lombok 插件提供,目的是简化构造者模式的代码。Builder Pattern 可轻松创建复杂对象;
###Protobuf
protocol buffers 是一种语言无关、平台无关、可扩展的序列化结构数据的方法,它可用于(数据)通信协议、数据存储等。相比 JSON,XML 占用内存小,解析速度更快。在使用过程中,首先创建 xx.proto 文件,通过 protobuf-maven-plugin 创建相应的类。
Guava
Guava 是一组来自谷歌的核心 Java 库,其中包括新的集合类型、不可变集合、一个图库,以及用于并发、I/O、散列、缓存、原语、字符串等的实用工具。
- ListenalbeFuture
ListenalbeFuture 是对 JDK 的 future 进行增强,可以监听任务的执行状况:
使用 MoreExecutors 创建线程池
ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
提交任务
final ListenableFuture<Integer> listenableFuture = executorService.submit(new Callable<Integer>() {public Integer call() throws Exception {System.out.println("call execute..");TimeUnit.SECONDS.sleep(3);return 7;}});
添加监听任务执行状态①
listenableFuture.addListener(()->{try {System.out.println(listenableFuture.get());} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}},executorService);
添加监听任务执行状态②
Futures.addCallback(listenableFuture, new FutureCallback<Integer>() {@Overridepublic void onSuccess(@Nullable Integer integer) {//返回future的执行结果}@Overridepublic void onFailure(Throwable throwable) {}}, executorService);
- Futures.transform
如果需要对返回值做处理,可以使用 Futures.transform 方法,它是同步方法,另外还有一个异步方法 Futures.transformAsync:
ListenableFuture<String> future = executorService.submit(() -> "hello, future");ListenableFuture<Integer> future2 = Futures.transform(future2, String::length, executorService);//future2返回的是’hello, future‘的长度
- SettableFuture
SettableFuture可以认为是一种异步转同步工具,可以它在指定时间内获取ListenableFuture的计算结果:
SettableFuture<Integer> settableFuture = SettableFuture.create();ListenableFuture<Integer> future11 = executorService.submit(() -> {int sum = 5 + 6;settableFuture.set(sum);return sum;});// get设置超时时间System.out.println(settableFuture.get(2, TimeUnit.SECONDS));
