├── pic ├── java-akka-remote-demo ├── Client │ ├── .gitignore │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ └── org.eclipse.jdt.core.prefs │ ├── src │ │ └── main │ │ │ ├── resources │ │ │ └── application.conf │ │ │ └── java │ │ │ └── example │ │ │ └── akka │ │ │ └── remote │ │ │ └── client │ │ │ ├── Client.java │ │ │ ├── CalculatorActor.java │ │ │ └── ClientActor.java │ ├── .project │ ├── pom.xml │ ├── Client.iml │ └── .classpath ├── Server │ ├── .gitignore │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ └── org.eclipse.jdt.core.prefs │ ├── src │ │ └── main │ │ │ ├── resources │ │ │ └── application.conf │ │ │ └── java │ │ │ └── example │ │ │ └── akka │ │ │ └── remote │ │ │ └── server │ │ │ ├── Server.java │ │ │ └── CalculatorActor.java │ ├── .project │ ├── pom.xml │ ├── Server.iml │ └── .classpath ├── Shared │ ├── .gitignore │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ └── org.eclipse.jdt.core.prefs │ ├── pom.xml │ ├── .project │ ├── src │ │ └── main │ │ │ └── java │ │ │ └── example │ │ │ └── akka │ │ │ └── remote │ │ │ └── shared │ │ │ ├── LoggingActor.java │ │ │ └── Messages.java │ ├── .classpath │ └── Shared.iml ├── .DS_Store ├── .settings │ └── org.eclipse.m2e.core.prefs ├── .project ├── pom.xml └── README.md ├── 公众号.jpg ├── dubbo-demo ├── .DS_Store ├── Sdk │ ├── .DS_Store │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ ├── org.eclipse.core.resources.prefs │ │ └── org.eclipse.jdt.core.prefs │ ├── src │ │ ├── main │ │ │ └── java │ │ │ │ ├── org │ │ │ │ └── Sdk │ │ │ │ │ └── App.java │ │ │ │ └── com │ │ │ │ └── books │ │ │ │ └── dubbo │ │ │ │ └── demo │ │ │ │ ├── api │ │ │ │ ├── GrettingServiceRpcContext.java │ │ │ │ ├── GreetingService.java │ │ │ │ ├── GrettingServiceAsync.java │ │ │ │ ├── PoJo.java │ │ │ │ └── Result.java │ │ │ │ └── test │ │ │ │ └── performance │ │ │ │ └── TestConsumerPerformance.java │ │ └── test │ │ │ └── java │ │ │ └── org │ │ │ └── Sdk │ │ │ └── AppTest.java │ ├── .project │ ├── .classpath │ └── pom.xml ├── .settings │ ├── org.eclipse.m2e.core.prefs │ ├── org.eclipse.core.resources.prefs │ └── org.eclipse.jdt.core.prefs ├── Consumer │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ ├── org.eclipse.core.resources.prefs │ │ └── org.eclipse.jdt.core.prefs │ ├── src │ │ ├── main │ │ │ ├── resources │ │ │ │ ├── META-INF │ │ │ │ │ └── dubbo │ │ │ │ │ │ ├── org.apache.dubbo.remoting.Dispatcher │ │ │ │ │ │ ├── org.apache.dubbo.common.threadpool.ThreadPool │ │ │ │ │ │ ├── org.apache.dubbo.rpc.cluster.Cluster │ │ │ │ │ │ └── org.apache.dubbo.rpc.cluster.LoadBalance │ │ │ │ └── log4j.properties │ │ │ └── java │ │ │ │ └── org │ │ │ │ └── apache │ │ │ │ └── dubbo │ │ │ │ └── demo │ │ │ │ └── consumer │ │ │ │ ├── APiAsyncConsumer.java │ │ │ │ ├── APiConsumerForProviderAsyncContext.java │ │ │ │ ├── APiConsumerForProviderAsync.java │ │ │ │ └── APiAsyncConsumerForCompletableFuture2.java │ │ └── test │ │ │ └── java │ │ │ └── org │ │ │ └── Consumer │ │ │ └── AppTest.java │ ├── .project │ ├── .classpath │ └── pom.xml ├── Provider │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ ├── org.eclipse.core.resources.prefs │ │ └── org.eclipse.jdt.core.prefs │ ├── src │ │ ├── main │ │ │ ├── resources │ │ │ │ ├── META-INF │ │ │ │ │ └── dubbo │ │ │ │ │ │ ├── org.apache.dubbo.remoting.Dispatcher │ │ │ │ │ │ └── org.apache.dubbo.common.threadpool.ThreadPool │ │ │ │ └── log4j.properties │ │ │ └── java │ │ │ │ └── com │ │ │ │ └── books │ │ │ │ └── dubbo │ │ │ │ └── demo │ │ │ │ └── provider │ │ │ │ ├── mydispatcher │ │ │ │ ├── MyDispatcher.java │ │ │ │ └── MyThreadPool.java │ │ │ │ ├── GreetingServiceImpl.java │ │ │ │ ├── ApiProviderForAsync.java │ │ │ │ ├── ApiProvider.java │ │ │ │ ├── ApiProviderForAsyncContext.java │ │ │ │ ├── GrettingServiceAsyncImpl.java │ │ │ │ ├── GrettingServiceAsyncContextImpl.java │ │ │ │ ├── ApiProviderForExecuteLimit.java │ │ │ │ └── APiConsumerInJvm.java │ │ └── test │ │ │ └── java │ │ │ └── org │ │ │ └── Provider │ │ │ └── AppTest.java │ ├── .project │ ├── .classpath │ └── pom.xml ├── src │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── books │ │ │ └── dubbo │ │ │ └── dem │ │ │ └── Demo │ │ │ └── App.java │ └── test │ │ └── java │ │ └── com │ │ └── books │ │ └── dubbo │ │ └── dem │ │ └── Demo │ │ └── AppTest.java ├── .project ├── .classpath └── pom.xml ├── async-program-demo ├── .settings │ ├── org.eclipse.m2e.core.prefs │ ├── org.eclipse.core.resources.prefs │ └── org.eclipse.jdt.core.prefs ├── Chapter5 │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ ├── org.eclipse.core.resources.prefs │ │ └── org.eclipse.jdt.core.prefs │ ├── .project │ ├── src │ │ ├── test │ │ │ └── java │ │ │ │ └── org │ │ │ │ └── Chapter5 │ │ │ │ └── AppTest.java │ │ └── main │ │ │ └── java │ │ │ └── org │ │ │ └── Chapter5 │ │ │ ├── reactor │ │ │ ├── AsyncRpcCall.java │ │ │ └── StreamTest.java │ │ │ └── rxjava │ │ │ ├── AsyncRpcCall3.java │ │ │ ├── AsyncRpcCall4.java │ │ │ ├── AsyncRpcCallromFuture.java │ │ │ ├── AsyncRpcCall.java │ │ │ ├── AsyncRpcCall6.java │ │ │ ├── AsyncRpcCall5.java │ │ │ ├── StreamTest.java │ │ │ └── AsyncRpcCall2.java │ ├── .classpath │ └── pom.xml ├── Chapter8 │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ ├── org.eclipse.core.resources.prefs │ │ └── org.eclipse.jdt.core.prefs │ ├── src │ │ ├── main │ │ │ └── java │ │ │ │ └── org │ │ │ │ └── Chapter8 │ │ │ │ ├── App.java │ │ │ │ ├── disruptor │ │ │ │ ├── LongEvent.java │ │ │ │ ├── LongEventFactory.java │ │ │ │ ├── JournalConsumer.java │ │ │ │ ├── ApplicationConsumer.java │ │ │ │ ├── ReplicationConsumer.java │ │ │ │ ├── LongEventProducer.java │ │ │ │ └── LongEventMain.java │ │ │ │ ├── netty │ │ │ │ ├── FutureMapUtil.java │ │ │ │ ├── AllChannelHandler.java │ │ │ │ ├── TestModelAsyncRpc4Reactive.java │ │ │ │ ├── TestModelAsyncRpc.java │ │ │ │ ├── TestModelAsyncRpc2.java │ │ │ │ ├── NettyClientHandler.java │ │ │ │ ├── RpcServer.java │ │ │ │ └── NettyServerHandler.java │ │ │ │ ├── akka │ │ │ │ ├── Client.java │ │ │ │ ├── Messages.java │ │ │ │ ├── CalculatorActor.java │ │ │ │ └── ClientActor.java │ │ │ │ └── metaq │ │ │ │ ├── ProducerSync.java │ │ │ │ ├── Producer.java │ │ │ │ ├── ProducerAsync.java │ │ │ │ └── Consumer.java │ │ └── test │ │ │ └── java │ │ │ └── org │ │ │ └── Chapter8 │ │ │ └── AppTest.java │ ├── .project │ ├── .classpath │ └── pom.xml ├── ChapterIV │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ ├── org.eclipse.core.resources.prefs │ │ └── org.eclipse.jdt.core.prefs │ ├── src │ │ ├── main │ │ │ ├── java │ │ │ │ └── org │ │ │ │ │ └── ChapterIV │ │ │ │ │ ├── App.java │ │ │ │ │ ├── TaskExecutor │ │ │ │ │ ├── MyAsyncUncaughtExceptionHandler.java │ │ │ │ │ ├── TestaskExecutor.java │ │ │ │ │ └── AsyncExecutorExample.java │ │ │ │ │ └── Async │ │ │ │ │ ├── TestaskExecutorException.java │ │ │ │ │ ├── TestaskExecutor.java │ │ │ │ │ └── AsyncAnnotationExample.java │ │ │ └── resources │ │ │ │ ├── beans-annotation.xml │ │ │ │ ├── beans-annotation2.xml │ │ │ │ ├── beans-annotation3.xml │ │ │ │ └── beans.xml │ │ └── test │ │ │ └── java │ │ │ └── org │ │ │ └── ChapterIV │ │ │ └── AppTest.java │ ├── .project │ ├── .classpath │ └── pom.xml ├── First-Chapter │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ ├── org.eclipse.core.resources.prefs │ │ └── org.eclipse.jdt.core.prefs │ ├── src │ │ ├── main │ │ │ └── java │ │ │ │ └── org │ │ │ │ └── First │ │ │ │ └── Chapter │ │ │ │ └── App.java │ │ └── test │ │ │ └── java │ │ │ └── org │ │ │ └── First │ │ │ └── Chapter │ │ │ └── AppTest.java │ ├── .project │ ├── pom.xml │ └── .classpath ├── Second-Chapter │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ ├── org.eclipse.core.resources.prefs │ │ └── org.eclipse.jdt.core.prefs │ ├── .project │ ├── src │ │ ├── main │ │ │ └── java │ │ │ │ └── org │ │ │ │ └── Second │ │ │ │ └── Chapter │ │ │ │ ├── Thread │ │ │ │ ├── SyncExample.java │ │ │ │ ├── AsyncThreadExample.java │ │ │ │ └── AsyncThreadExample2.java │ │ │ │ └── ThreadPool │ │ │ │ ├── AsyncThreadPoolExample3.java │ │ │ │ ├── NamedThreadFactory.java │ │ │ │ ├── AsyncThreadPoolExample1.java │ │ │ │ └── AsyncThreadPoolExample2.java │ │ └── test │ │ │ └── java │ │ │ └── org │ │ │ └── Second │ │ │ └── Chapter │ │ │ └── AppTest.java │ ├── .classpath │ └── pom.xml ├── Third-Chapter │ ├── .settings │ │ ├── org.eclipse.m2e.core.prefs │ │ ├── org.eclipse.core.resources.prefs │ │ └── org.eclipse.jdt.core.prefs │ ├── src │ │ ├── main │ │ │ └── java │ │ │ │ └── org │ │ │ │ └── Third │ │ │ │ └── Chapter │ │ │ │ ├── App.java │ │ │ │ ├── CompletableFuture │ │ │ │ ├── StreamTestFuture.java │ │ │ │ ├── TestFutureException2.java │ │ │ │ ├── StreamTestFuture2.java │ │ │ │ ├── TestCompletableFutureCallBack.java │ │ │ │ ├── TestCompletableFutureWhenComplete.java │ │ │ │ ├── StreamTest.java │ │ │ │ ├── TestTwoCompletableFuture.java │ │ │ │ ├── TestCompletableFutureSet.java │ │ │ │ ├── TestCompletableFutureModelAsync.java │ │ │ │ ├── TestMoreCompletableFuture.java │ │ │ │ └── TestFutureException.java │ │ │ │ └── FutureTask │ │ │ │ ├── AsyncFutureExample.java │ │ │ │ ├── AsyncFutureExample3.java │ │ │ │ └── AsyncFutureExample2.java │ │ └── test │ │ │ └── java │ │ │ └── org │ │ │ └── Third │ │ │ └── Chapter │ │ │ └── AppTest.java │ ├── .project │ ├── .classpath │ └── pom.xml ├── src │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── jiaduo │ │ │ └── com │ │ │ └── async_program_demo │ │ │ └── App.java │ └── test │ │ └── java │ │ └── com │ │ └── jiaduo │ │ └── com │ │ └── async_program_demo │ │ └── AppTest.java ├── .project ├── .classpath └── pom.xml └── README.md /pic: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Client/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Server/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Shared/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /公众号.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhailuxu/async-program-demo/HEAD/公众号.jpg -------------------------------------------------------------------------------- /dubbo-demo/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhailuxu/async-program-demo/HEAD/dubbo-demo/.DS_Store -------------------------------------------------------------------------------- /dubbo-demo/Sdk/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhailuxu/async-program-demo/HEAD/dubbo-demo/Sdk/.DS_Store -------------------------------------------------------------------------------- /java-akka-remote-demo/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhailuxu/async-program-demo/HEAD/java-akka-remote-demo/.DS_Store -------------------------------------------------------------------------------- /dubbo-demo/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /dubbo-demo/Sdk/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /async-program-demo/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /dubbo-demo/Consumer/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /dubbo-demo/Consumer/src/main/resources/META-INF/dubbo/org.apache.dubbo.remoting.Dispatcher: -------------------------------------------------------------------------------- 1 | mydispatcher=com.books.dubbo.demo.provider.mydispatcher.MyDispatcher -------------------------------------------------------------------------------- /dubbo-demo/Provider/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/src/main/resources/META-INF/dubbo/org.apache.dubbo.remoting.Dispatcher: -------------------------------------------------------------------------------- 1 | mydispatcher=com.books.dubbo.demo.provider.mydispatcher.MyDispatcher -------------------------------------------------------------------------------- /java-akka-remote-demo/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /dubbo-demo/Consumer/src/main/resources/META-INF/dubbo/org.apache.dubbo.common.threadpool.ThreadPool: -------------------------------------------------------------------------------- 1 | mythreadpool=com.books.dubbo.demo.provider.mydispatcher.MyThreadPool -------------------------------------------------------------------------------- /dubbo-demo/Provider/src/main/resources/META-INF/dubbo/org.apache.dubbo.common.threadpool.ThreadPool: -------------------------------------------------------------------------------- 1 | mythreadpool=com.books.dubbo.demo.provider.mydispatcher.MyThreadPool -------------------------------------------------------------------------------- /dubbo-demo/Sdk/src/main/java/org/Sdk/App.java: -------------------------------------------------------------------------------- 1 | package org.Sdk; 2 | 3 | /** 4 | * Hello world! 5 | * 6 | */ 7 | public class App 8 | { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Client/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Server/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Shared/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /async-program-demo/First-Chapter/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /async-program-demo/Second-Chapter/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /dubbo-demo/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/test/java=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /dubbo-demo/Sdk/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/test/java=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /async-program-demo/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/test/java=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /dubbo-demo/Consumer/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=INFO,A1 2 | log4j.appender.A1=org.apache.log4j.ConsoleAppender 3 | log4j.appender.A1.layout=org.apache.log4j.PatternLayout -------------------------------------------------------------------------------- /dubbo-demo/Provider/src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=INFO,A1 2 | log4j.appender.A1=org.apache.log4j.ConsoleAppender 3 | log4j.appender.A1.layout=org.apache.log4j.PatternLayout -------------------------------------------------------------------------------- /async-program-demo/Chapter5/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/test/java=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/test/java=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/test/java=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /dubbo-demo/Consumer/src/main/resources/META-INF/dubbo/org.apache.dubbo.rpc.cluster.Cluster: -------------------------------------------------------------------------------- 1 | myCluster=org.apache.dubbo.demo.cluster.MyCluster 2 | myBroadcast=com.books.dubbo.demo.broadcast.BroadcastCluster -------------------------------------------------------------------------------- /async-program-demo/First-Chapter/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/test/java=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /async-program-demo/Second-Chapter/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/test/java=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/test/java=UTF-8 4 | encoding/=UTF-8 5 | -------------------------------------------------------------------------------- /dubbo-demo/Sdk/src/main/java/com/books/dubbo/demo/api/GrettingServiceRpcContext.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.api; 2 | 3 | public interface GrettingServiceRpcContext { 4 | String sayHello(String name); 5 | } -------------------------------------------------------------------------------- /dubbo-demo/Consumer/src/main/resources/META-INF/dubbo/org.apache.dubbo.rpc.cluster.LoadBalance: -------------------------------------------------------------------------------- 1 | myLoadBalance=com.books.dubbo.demo.loadbalance.MyLoadBalance 2 | myroundrobin=org.apache.dubbo.demo.cluster.MyLoadBalance -------------------------------------------------------------------------------- /dubbo-demo/Consumer/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/main/resources=UTF-8 4 | encoding//src/test/java=UTF-8 5 | encoding/=UTF-8 6 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/main/resources=UTF-8 4 | encoding//src/test/java=UTF-8 5 | encoding/=UTF-8 6 | -------------------------------------------------------------------------------- /dubbo-demo/Sdk/src/main/java/com/books/dubbo/demo/api/GreetingService.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.api; 2 | 3 | public interface GreetingService { 4 | String sayHello(String name); 5 | 6 | Result testGeneric(PoJo poJo); 7 | } 8 | -------------------------------------------------------------------------------- /dubbo-demo/Sdk/src/main/java/com/books/dubbo/demo/api/GrettingServiceAsync.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.api; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | 5 | public interface GrettingServiceAsync { 6 | CompletableFuture sayHello(String name); 7 | } -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/App.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8; 2 | 3 | /** 4 | * Hello world! 5 | * 6 | */ 7 | public class App 8 | { 9 | public static void main( String[] args ) 10 | { 11 | System.out.println( "Hello World!" ); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/src/main/java/org/ChapterIV/App.java: -------------------------------------------------------------------------------- 1 | package org.ChapterIV; 2 | 3 | /** 4 | * Hello world! 5 | * 6 | */ 7 | public class App 8 | { 9 | public static void main( String[] args ) 10 | { 11 | System.out.println( "Hello World!" ); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /dubbo-demo/src/main/java/com/books/dubbo/dem/Demo/App.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.dem.Demo; 2 | 3 | /** 4 | * Hello world! 5 | * 6 | */ 7 | public class App 8 | { 9 | public static void main( String[] args ) 10 | { 11 | System.out.println( "Hello World!" ); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/disruptor/LongEvent.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.disruptor; 2 | 3 | public class LongEvent { 4 | private long value; 5 | 6 | public void set(long value) { 7 | this.value = value; 8 | } 9 | 10 | public long get() { 11 | return value; 12 | } 13 | } -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/disruptor/LongEventFactory.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.disruptor; 2 | 3 | import com.lmax.disruptor.EventFactory; 4 | 5 | public class LongEventFactory implements EventFactory { 6 | public LongEvent newInstance() { 7 | return new LongEvent(); 8 | } 9 | } -------------------------------------------------------------------------------- /async-program-demo/First-Chapter/src/main/java/org/First/Chapter/App.java: -------------------------------------------------------------------------------- 1 | package org.First.Chapter; 2 | 3 | /** 4 | * Hello world! 5 | * 6 | */ 7 | public class App 8 | { 9 | public static void main( String[] args ) 10 | { 11 | System.out.println( "Hello World!" ); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/App.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter; 2 | 3 | /** 4 | * Hello world! 5 | * 6 | */ 7 | public class App 8 | { 9 | public static void main( String[] args ) 10 | { 11 | System.out.println( "Hello World!" ); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Shared/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 3 | org.eclipse.jdt.core.compiler.compliance=1.5 4 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 5 | org.eclipse.jdt.core.compiler.source=1.5 6 | -------------------------------------------------------------------------------- /async-program-demo/First-Chapter/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 3 | org.eclipse.jdt.core.compiler.compliance=1.5 4 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 5 | org.eclipse.jdt.core.compiler.source=1.5 6 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Client/src/main/resources/application.conf: -------------------------------------------------------------------------------- 1 | akka { 2 | actor { 3 | provider = "akka.remote.RemoteActorRefProvider" 4 | } 5 | remote { 6 | enabled-transports = ["akka.remote.netty.tcp"] 7 | netty.tcp { 8 | hostname = "127.0.0.1" 9 | port = 2553 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /async-program-demo/src/main/java/com/jiaduo/com/async_program_demo/App.java: -------------------------------------------------------------------------------- 1 | package com.jiaduo.com.async_program_demo; 2 | 3 | /** 4 | * Hello world! 5 | * 6 | */ 7 | public class App 8 | { 9 | public static void main( String[] args ) 10 | { 11 | System.out.println( "Hello World!" ); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Server/src/main/resources/application.conf: -------------------------------------------------------------------------------- 1 | akka { 2 | actor { 3 | provider = "akka.remote.RemoteActorRefProvider" 4 | 5 | 6 | } 7 | remote { 8 | enabled-transports = ["akka.remote.netty.tcp"] 9 | netty.tcp { 10 | hostname = "127.0.0.1" 11 | port = 2552 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/disruptor/JournalConsumer.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.disruptor; 2 | 3 | import com.lmax.disruptor.EventHandler; 4 | 5 | public class JournalConsumer implements EventHandler { 6 | public void onEvent(LongEvent event, long sequence, boolean endOfBatch) { 7 | System.out.println(Thread.currentThread().getName() + "Persist Event: " + event.get()); 8 | } 9 | } -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/disruptor/ApplicationConsumer.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.disruptor; 2 | 3 | import com.lmax.disruptor.EventHandler; 4 | 5 | public class ApplicationConsumer implements EventHandler { 6 | public void onEvent(LongEvent event, long sequence, boolean endOfBatch) { 7 | System.out.println(Thread.currentThread().getName() + "Application Event: " + event.get()); 8 | } 9 | } -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/disruptor/ReplicationConsumer.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.disruptor; 2 | 3 | import com.lmax.disruptor.EventHandler; 4 | 5 | public class ReplicationConsumer implements EventHandler { 6 | public void onEvent(LongEvent event, long sequence, boolean endOfBatch) { 7 | System.out.println(Thread.currentThread().getName() + "Replication Event: " + event.get()); 8 | } 9 | } -------------------------------------------------------------------------------- /dubbo-demo/Sdk/src/main/java/com/books/dubbo/demo/api/PoJo.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.api; 2 | 3 | public class PoJo { 4 | 5 | private String id; 6 | public String getId() { 7 | return id; 8 | } 9 | public void setId(String id) { 10 | this.id = id; 11 | } 12 | public String getName() { 13 | return name; 14 | } 15 | public void setName(String name) { 16 | this.name = name; 17 | } 18 | private String name; 19 | } 20 | -------------------------------------------------------------------------------- /java-akka-remote-demo/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Remote 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.m2e.core.maven2Builder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.m2e.core.maven2Nature 16 | 17 | 18 | -------------------------------------------------------------------------------- /dubbo-demo/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.compliance=1.8 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.8 9 | -------------------------------------------------------------------------------- /dubbo-demo/Sdk/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.compliance=1.8 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.8 9 | -------------------------------------------------------------------------------- /async-program-demo/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.compliance=1.8 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.8 9 | -------------------------------------------------------------------------------- /dubbo-demo/Consumer/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.compliance=1.8 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.8 9 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.compliance=1.8 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.8 9 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.compliance=1.8 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.8 9 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.compliance=1.8 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.8 9 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.compliance=1.8 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.8 9 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.compliance=1.8 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.8 9 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Client/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 4 | org.eclipse.jdt.core.compiler.compliance=1.5 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.5 9 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Server/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 4 | org.eclipse.jdt.core.compiler.compliance=1.5 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.5 9 | -------------------------------------------------------------------------------- /async-program-demo/Second-Chapter/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.compliance=1.8 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.8 9 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Server/src/main/java/example/akka/remote/server/Server.java: -------------------------------------------------------------------------------- 1 | package example.akka.remote.server; 2 | 3 | import akka.actor.ActorSystem; 4 | import akka.actor.Props; 5 | import com.typesafe.config.ConfigFactory; 6 | 7 | public class Server { 8 | 9 | public static void main(String... args) { 10 | // 1. 创建Actor系统 11 | ActorSystem system = ActorSystem.create("AkkaRemoteServer", ConfigFactory.load()); 12 | 13 | // 2. 创建Actor 14 | system.actorOf(Props.create(CalculatorActor.class), "CalculatorActor"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Shared/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | Remote 7 | akka 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | Shared 13 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/src/main/java/org/ChapterIV/TaskExecutor/MyAsyncUncaughtExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package org.ChapterIV.TaskExecutor; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; 6 | 7 | public class MyAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler { 8 | 9 | @Override 10 | public void handleUncaughtException(Throwable ex, Method method, Object... params) { 11 | // handle exception 12 | System.out.println(ex.getLocalizedMessage()); 13 | } 14 | } -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/netty/FutureMapUtil.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.netty; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ConcurrentHashMap; 5 | 6 | public class FutureMapUtil { 7 | // <请求id,对应的future> 8 | private static final ConcurrentHashMap futureMap = new ConcurrentHashMap(); 9 | 10 | public static void put(String id, CompletableFuture future) { 11 | futureMap.put(id, future); 12 | } 13 | 14 | public static CompletableFuture remove(String id) { 15 | return futureMap.remove(id); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /dubbo-demo/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Demo 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /dubbo-demo/Sdk/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Sdk 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /dubbo-demo/Consumer/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Consumer 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Provider 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/src/main/java/com/books/dubbo/demo/provider/mydispatcher/MyDispatcher.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.provider.mydispatcher; 2 | 3 | import org.apache.dubbo.common.URL; 4 | import org.apache.dubbo.remoting.ChannelHandler; 5 | import org.apache.dubbo.remoting.Dispatcher; 6 | import org.apache.dubbo.remoting.transport.dispatcher.all.AllChannelHandler; 7 | 8 | public class MyDispatcher implements Dispatcher { 9 | 10 | public static final String NAME = "mydispatcher"; 11 | 12 | @Override 13 | public ChannelHandler dispatch(ChannelHandler handler, URL url) { 14 | return new AllChannelHandler(handler, url); 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /java-akka-remote-demo/Client/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Client 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Server/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Server 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Shared/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Shared 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /async-program-demo/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | async-program-demo 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Chapter5 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Chapter8 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Chapter4 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/akka/Client.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.akka; 2 | 3 | import akka.actor.ActorRef; 4 | import akka.actor.ActorSystem; 5 | import akka.actor.Props; 6 | import com.typesafe.config.ConfigFactory; 7 | 8 | public class Client { 9 | public static void main(String[] args) { 10 | // 1. 创建Actor系统,会加载application.conf文件 11 | ActorSystem system = ActorSystem.create("AkkaRemoteClient", ConfigFactory.load()); 12 | 13 | // 2. 创建Actor 14 | ActorRef client = system.actorOf(Props.create(ClientActor.class)); 15 | 16 | // 3. 发送消息 17 | client.tell("DoCalcs", ActorRef.noSender()); 18 | System.out.println("over"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/disruptor/LongEventProducer.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.disruptor; 2 | 3 | import com.lmax.disruptor.RingBuffer; 4 | 5 | public class LongEventProducer { 6 | private final RingBuffer ringBuffer; 7 | 8 | public LongEventProducer(RingBuffer ringBuffer) { 9 | this.ringBuffer = ringBuffer; 10 | } 11 | 12 | public void onData(long bb) { 13 | long sequence = ringBuffer.next(); // 8.1 第一阶段,获取序列号 14 | try { 15 | LongEvent event = ringBuffer.get(sequence); // 8.2获取序列号对应的实体元素 16 | event.set(bb); // 8.3修改元素的值 17 | } finally { 18 | ringBuffer.publish(sequence);// 8.4发布元素。 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /async-program-demo/Second-Chapter/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Chapter2 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Chapter3 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /async-program-demo/First-Chapter/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | First-Chapter 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Client/src/main/java/example/akka/remote/client/Client.java: -------------------------------------------------------------------------------- 1 | package example.akka.remote.client; 2 | 3 | import akka.actor.ActorRef; 4 | import akka.actor.ActorSystem; 5 | import akka.actor.Props; 6 | import com.typesafe.config.ConfigFactory; 7 | 8 | public class Client { 9 | public static void main(String[] args) { 10 | // 1. 创建Actor系统,会加载application.conf文件 11 | ActorSystem system = ActorSystem.create("AkkaRemoteClient", ConfigFactory.load()); 12 | 13 | // 2. 创建Actor 14 | ActorRef client = system.actorOf(Props.create(ClientActor.class)); 15 | 16 | // 3. 发送消息 17 | client.tell("DoCalcs", ActorRef.noSender()); 18 | System.out.println("over"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/netty/AllChannelHandler.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.netty; 2 | 3 | import java.util.concurrent.SynchronousQueue; 4 | import java.util.concurrent.ThreadPoolExecutor; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | public class AllChannelHandler { 8 | 9 | // 使用JDK的ThreadPoolExecutor线程池创建一个线程池 10 | private static ThreadPoolExecutor executor = new ThreadPoolExecutor(8, 8, 1, TimeUnit.MINUTES, 11 | new SynchronousQueue<>(), new ThreadPoolExecutor.CallerRunsPolicy()); 12 | 13 | // 异步执行任务 14 | public static void channelRead(Runnable r) { 15 | executor.execute(r); 16 | } 17 | 18 | // 关闭线程池 19 | public static void shutdown() { 20 | executor.shutdown(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /dubbo-demo/Sdk/src/main/java/com/books/dubbo/demo/api/Result.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.api; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Result implements Serializable { 6 | 7 | private static final long serialVersionUID = 1L; 8 | private T data; 9 | 10 | public T getData() { 11 | return data; 12 | } 13 | 14 | public void setData(T data) { 15 | this.data = data; 16 | } 17 | 18 | public boolean isSucess() { 19 | return sucess; 20 | } 21 | 22 | public void setSucess(boolean sucess) { 23 | this.sucess = sucess; 24 | } 25 | 26 | public String getMsg() { 27 | return msg; 28 | } 29 | 30 | public void setMsg(String msg) { 31 | this.msg = msg; 32 | } 33 | 34 | private boolean sucess; 35 | private String msg; 36 | } 37 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Shared/src/main/java/example/akka/remote/shared/LoggingActor.java: -------------------------------------------------------------------------------- 1 | package example.akka.remote.shared; 2 | 3 | import akka.actor.UntypedActor; 4 | import akka.event.Logging; 5 | import akka.event.LoggingAdapter; 6 | 7 | import java.io.Serializable; 8 | 9 | /** 10 | * This actor logs to the console. 11 | * Intented to run on a remote actorsystem for testing. 12 | */ 13 | public class LoggingActor extends UntypedActor implements Serializable { 14 | private LoggingAdapter log = Logging.getLogger(getContext().system(), this); 15 | 16 | @Override 17 | public void onReceive(Object message) throws Exception { 18 | if (message instanceof String) { 19 | log.info("Got message: " + message); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Client/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | Remote 7 | akka 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | Client 13 | 14 | 15 | 16 | Shared 17 | akka 18 | 1.0-SNAPSHOT 19 | 20 | 21 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Server/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | Remote 7 | akka 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | Server 13 | 14 | 15 | 16 | Shared 17 | akka 18 | 1.0-SNAPSHOT 19 | 20 | 21 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/akka/Messages.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.akka; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Messages { 6 | // 加法域对象 7 | public static class Sum implements Serializable { 8 | private int first; 9 | private int second; 10 | 11 | public Sum(int first, int second) { 12 | this.first = first; 13 | this.second = second; 14 | } 15 | 16 | public int getFirst() { 17 | return first; 18 | } 19 | 20 | public int getSecond() { 21 | return second; 22 | } 23 | } 24 | 25 | // 存放计算结果的域对象 26 | public static class Result implements Serializable { 27 | private int result; 28 | 29 | public Result(int result) { 30 | this.result = result; 31 | } 32 | 33 | public int getResult() { 34 | return result; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/src/main/java/org/ChapterIV/Async/TestaskExecutorException.java: -------------------------------------------------------------------------------- 1 | package org.ChapterIV.Async; 2 | 3 | import org.springframework.context.support.ClassPathXmlApplicationContext; 4 | 5 | public class TestaskExecutorException { 6 | 7 | public static void main(String arg[]) throws Exception { 8 | // 1.创建容器上下文 9 | ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext( 10 | new String[] { "beans-annotation.xml" }); 11 | 12 | // 2. 获取AsyncExecutorExample实例并调用打印方法 13 | System.out.println(Thread.currentThread().getName() + " begin "); 14 | AsyncAnnotationExample asyncCommentExample = applicationContext.getBean(AsyncAnnotationExample.class); 15 | asyncCommentExample.testException(); 16 | System.out.println(Thread.currentThread().getName() + " end "); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Shared/src/main/java/example/akka/remote/shared/Messages.java: -------------------------------------------------------------------------------- 1 | package example.akka.remote.shared; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Messages { 6 | // 加法域对象 7 | public static class Sum implements Serializable { 8 | private int first; 9 | private int second; 10 | 11 | public Sum(int first, int second) { 12 | this.first = first; 13 | this.second = second; 14 | } 15 | 16 | public int getFirst() { 17 | return first; 18 | } 19 | 20 | public int getSecond() { 21 | return second; 22 | } 23 | } 24 | 25 | // 存放计算结果的域对象 26 | public static class Result implements Serializable { 27 | private int result; 28 | 29 | public Result(int result) { 30 | this.result = result; 31 | } 32 | 33 | public int getResult() { 34 | return result; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /dubbo-demo/Sdk/src/test/java/org/Sdk/AppTest.java: -------------------------------------------------------------------------------- 1 | package org.Sdk; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /dubbo-demo/Consumer/src/test/java/org/Consumer/AppTest.java: -------------------------------------------------------------------------------- 1 | package org.Consumer; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/src/test/java/org/Provider/AppTest.java: -------------------------------------------------------------------------------- 1 | package org.Provider; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/src/test/java/org/Chapter5/AppTest.java: -------------------------------------------------------------------------------- 1 | package org.Chapter5; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/test/java/org/Chapter8/AppTest.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/src/main/resources/beans-annotation.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | 16 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/src/test/java/org/ChapterIV/AppTest.java: -------------------------------------------------------------------------------- 1 | package org.ChapterIV; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /dubbo-demo/src/test/java/com/books/dubbo/dem/Demo/AppTest.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.dem.Demo; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /async-program-demo/First-Chapter/src/test/java/org/First/Chapter/AppTest.java: -------------------------------------------------------------------------------- 1 | package org.First.Chapter; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/test/java/org/Third/Chapter/AppTest.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /async-program-demo/Second-Chapter/src/main/java/org/Second/Chapter/Thread/SyncExample.java: -------------------------------------------------------------------------------- 1 | package org.Second.Chapter.Thread; 2 | 3 | public class SyncExample { 4 | 5 | public static void doSomethingA() { 6 | 7 | try { 8 | Thread.sleep(2000); 9 | } catch (InterruptedException e) { 10 | e.printStackTrace(); 11 | } 12 | System.out.println("--- doSomethingA---"); 13 | } 14 | 15 | public static void doSomethingB() { 16 | try { 17 | Thread.sleep(2000); 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | System.out.println("--- doSomethingB---"); 22 | 23 | } 24 | 25 | public static void main(String[] args) { 26 | 27 | long start = System.currentTimeMillis(); 28 | // 1.执行任务A 29 | doSomethingA(); 30 | 31 | // 2.执行任务B 32 | doSomethingB(); 33 | 34 | System.out.println(System.currentTimeMillis() - start); 35 | 36 | } 37 | } -------------------------------------------------------------------------------- /async-program-demo/Second-Chapter/src/test/java/org/Second/Chapter/AppTest.java: -------------------------------------------------------------------------------- 1 | package org.Second.Chapter; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/src/main/java/org/ChapterIV/TaskExecutor/TestaskExecutor.java: -------------------------------------------------------------------------------- 1 | package org.ChapterIV.TaskExecutor; 2 | 3 | import org.springframework.context.support.ClassPathXmlApplicationContext; 4 | 5 | public class TestaskExecutor { 6 | 7 | public static void main(String arg[]) throws InterruptedException { 8 | // 1.创建容器上下文 9 | ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext( 10 | new String[] { "beans.xml" }); 11 | 12 | // 2. 获取AsyncExecutorExample实例并调用打印方法 13 | System.out.println(Thread.currentThread().getName() + " begin "); 14 | AsyncExecutorExample asyncExecutorExample = applicationContext.getBean(AsyncExecutorExample.class); 15 | asyncExecutorExample.printMessages(); 16 | System.out.println(Thread.currentThread().getName() + " end "); 17 | 18 | // 3.关闭执行器,释放线程 19 | asyncExecutorExample.shutdown(); 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /async-program-demo/src/test/java/com/jiaduo/com/async_program_demo/AppTest.java: -------------------------------------------------------------------------------- 1 | package com.jiaduo.com.async_program_demo; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /java-akka-remote-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | akka 8 | Remote 9 | pom 10 | 1.0-SNAPSHOT 11 | 12 | Client 13 | Server 14 | Shared 15 | 16 | 17 | 18 | 19 | 20 | com.typesafe.akka 21 | akka-remote_2.11 22 | 2.3.7 23 | 24 | 25 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/netty/TestModelAsyncRpc4Reactive.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.netty; 2 | 3 | import java.util.concurrent.ExecutionException; 4 | 5 | import io.reactivex.Flowable; 6 | 7 | public class TestModelAsyncRpc4Reactive { 8 | // 1.创建rpc客户端 9 | private static final RpcClient rpcClient = new RpcClient(); 10 | 11 | public static void main(String[] args) throws InterruptedException, ExecutionException { 12 | 13 | // 2.发起远程调用异步,并注册回调,马上返回 14 | Flowable result = rpcClient.rpcAsyncCallFlowable4("who are you"); 15 | 16 | //3.订阅流对象 17 | result.subscribe(/* onNext */r -> { 18 | System.out.println(Thread.currentThread().getName() + ":" + r); 19 | }, /* onError */error -> { 20 | System.out.println(Thread.currentThread().getName() + "error:" + error.getLocalizedMessage()); 21 | }); 22 | 23 | System.out.println("---async rpc call over"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/netty/TestModelAsyncRpc.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.netty; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ExecutionException; 5 | 6 | import io.reactivex.Flowable; 7 | 8 | public class TestModelAsyncRpc { 9 | 10 | private static final RpcClient rpcClient = new RpcClient(); 11 | 12 | public static void main(String[] args) throws InterruptedException, ExecutionException { 13 | 14 | // 1.同步调用 15 | System.out.println(rpcClient.rpcSyncCall("who are you")); 16 | 17 | // 2.发起远程调用异步,并注册回调,马上返回 18 | CompletableFuture future = rpcClient.rpcAsyncCall("who are you"); 19 | 20 | 21 | 22 | future.whenComplete((v, t) -> { 23 | if (t != null) { 24 | t.printStackTrace(); 25 | } else { 26 | System.out.println(v); 27 | } 28 | 29 | }); 30 | 31 | System.out.println("---async rpc call over"); 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /dubbo-demo/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/src/main/java/com/books/dubbo/demo/provider/GreetingServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.provider; 2 | 3 | import java.io.IOException; 4 | 5 | import org.apache.dubbo.common.json.JSON; 6 | import org.apache.dubbo.rpc.RpcContext; 7 | 8 | import com.books.dubbo.demo.api.GreetingService; 9 | import com.books.dubbo.demo.api.PoJo; 10 | import com.books.dubbo.demo.api.Result; 11 | 12 | public class GreetingServiceImpl implements GreetingService { 13 | 14 | @Override 15 | public String sayHello(String name) { 16 | 17 | try { 18 | Thread.sleep(1000); 19 | } catch (InterruptedException e) { 20 | e.printStackTrace(); 21 | } 22 | return name; 23 | } 24 | 25 | @Override 26 | public Result testGeneric(PoJo poJo) { 27 | Result result = new Result(); 28 | result.setSucess(true); 29 | try { 30 | result.setData(JSON.json(poJo)); 31 | } catch (IOException e) { 32 | e.printStackTrace(); 33 | } 34 | 35 | return result; 36 | } 37 | } -------------------------------------------------------------------------------- /async-program-demo/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /async-program-demo/Second-Chapter/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /async-program-demo/First-Chapter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.jiaduo.async.demo 7 | async-program-demo 8 | 0.0.1-SNAPSHOT 9 | 10 | com.jiaduo.com 11 | First-Chapter 12 | 0.0.1-SNAPSHOT 13 | First-Chapter 14 | http://maven.apache.org 15 | 16 | UTF-8 17 | 18 | 19 | 20 | junit 21 | junit 22 | 3.8.1 23 | test 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.jiaduo.async.demo 7 | async-program-demo 8 | 0.0.1-SNAPSHOT 9 | 10 | com.jiaduo.async.demo 11 | Third-Chapter 12 | 0.0.1-SNAPSHOT 13 | Third-Chapter 14 | http://maven.apache.org 15 | 16 | UTF-8 17 | 18 | 19 | 20 | junit 21 | junit 22 | 3.8.1 23 | test 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /async-program-demo/Second-Chapter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.jiaduo.async.demo 7 | async-program-demo 8 | 0.0.1-SNAPSHOT 9 | 10 | com.jiaduo.async.demo 11 | Second-Chapter 12 | 0.0.1-SNAPSHOT 13 | Second-Chapter 14 | http://maven.apache.org 15 | 16 | UTF-8 17 | 18 | 19 | 20 | junit 21 | junit 22 | 3.8.1 23 | test 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Server/src/main/java/example/akka/remote/server/CalculatorActor.java: -------------------------------------------------------------------------------- 1 | package example.akka.remote.server; 2 | 3 | import akka.actor.ActorRef; 4 | import akka.actor.Props; 5 | import akka.actor.UntypedActor; 6 | import akka.event.Logging; 7 | import akka.event.LoggingAdapter; 8 | import example.akka.remote.shared.LoggingActor; 9 | 10 | import static example.akka.remote.shared.Messages.*; 11 | 12 | public class CalculatorActor extends UntypedActor { 13 | 14 | private LoggingAdapter log = Logging.getLogger(getContext().system(), this); 15 | 16 | 17 | @Override 18 | public void onReceive(Object message) throws Exception { 19 | log.info("onReceive({})", message); 20 | 21 | if (message instanceof Sum) { 22 | log.info("got a Sum message"); 23 | Sum sum = (Sum) message; 24 | 25 | int result = sum.getFirst() + sum.getSecond(); 26 | getSender().tell(new Result(result), getSelf()); 27 | 28 | } else { 29 | unhandled(message); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/CompletableFuture/StreamTestFuture.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter.CompletableFuture; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class StreamTestFuture { 7 | 8 | public static String rpcCall(String ip, String param) { 9 | 10 | System.out.println(ip + " rpcCall:" + param); 11 | try { 12 | Thread.sleep(1000); 13 | } catch (InterruptedException e) { 14 | e.printStackTrace(); 15 | } 16 | return param; 17 | 18 | } 19 | 20 | public static void main(String[] args) { 21 | 22 | // 1.生成ip列表 23 | List ipList = new ArrayList(); 24 | for (int i = 1; i <= 10; ++i) { 25 | ipList.add("192.168.0." + i); 26 | } 27 | 28 | // 2.发起广播调用 29 | long start = System.currentTimeMillis(); 30 | List result = new ArrayList<>(); 31 | for (String ip : ipList) { 32 | result.add(rpcCall(ip, ip)); 33 | } 34 | 35 | // 3.输出 36 | result.stream().forEach(r -> System.out.println(r)); 37 | System.out.println("cost:" + (System.currentTimeMillis() - start)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /java-akka-remote-demo/README.md: -------------------------------------------------------------------------------- 1 | Akka Remote Example in Java 2 | ========================= 3 | 4 | ## Introduction 5 | This project was made while testing the Akka Remoting features. 6 | It contains three modules; a Client, a Server and a LoggerEnvironment. The two types of Akka Remoting are tested; Creation and Lookup. 7 | 8 | ##### Client 9 | The client uses remote lookup to get an `ActorSelection` of a Remote Actor (running on the Server.) and sends a message to it. 10 | 11 | ##### Server 12 | The server creates a `CalculatorActor` and handles incoming messages. 13 | The server also creates a `LoggingActor` which is (remotely) deployed on the `LoggerEnvironment`. 14 | 15 | ##### LoggerEnvironment 16 | Essentially nothing more than a container. The server will create an actor on this environment. 17 | 18 | ## How to run 19 | You can run the program like every ordinary Java main program. Make sure you have `mvn clean install`ed the project before to get the Akka dependency. 20 | It's important to run the projects in the following order: 21 | 22 | 1. LoggerEnvironment 23 | 2. Server 24 | 3. Client 25 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/netty/TestModelAsyncRpc2.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.netty; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ExecutionException; 5 | 6 | public class TestModelAsyncRpc2 { 7 | 8 | private static final RpcClient rpcClient = new RpcClient(); 9 | 10 | public static void main(String[] args) throws InterruptedException, ExecutionException { 11 | 12 | // 1.发起远程调用异步,并注册回调,马上返回 13 | CompletableFuture future1 = rpcClient.rpcAsyncCall("who are you"); 14 | // 2.发起远程调用异步,并注册回调,马上返回 15 | CompletableFuture future2 = rpcClient.rpcAsyncCall("who are you"); 16 | 17 | // 3.等两个请求都返回结果时候,使用结果做些事情 18 | CompletableFuture future = future1.thenCombine(future2, (u, v) -> { 19 | 20 | return u + v; 21 | }); 22 | 23 | // 4.等待最终结果 24 | future.whenComplete((v, t) -> { 25 | if (t != null) { 26 | t.printStackTrace(); 27 | } else { 28 | System.out.println(v); 29 | } 30 | 31 | }); 32 | System.out.println("---async rpc call over---"); 33 | // rpcClient.close(); 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /dubbo-demo/Sdk/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Shared/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /async-program-demo/First-Chapter/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/akka/CalculatorActor.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.akka; 2 | 3 | import akka.actor.ActorRef; 4 | import akka.actor.Props; 5 | import akka.actor.UntypedActor; 6 | import akka.event.Logging; 7 | import akka.event.LoggingAdapter; 8 | 9 | import static org.Chapter8.akka.Messages.*; 10 | 11 | public class CalculatorActor extends UntypedActor { 12 | 13 | private LoggingAdapter log = Logging.getLogger(getContext().system(), this); 14 | 15 | // private ActorRef loggingActor = 16 | // getContext().actorOf(Props.create(LoggingActor.class), "LoggingActor"); 17 | 18 | @Override 19 | public void onReceive(Object message) throws Exception { 20 | log.info("onReceive({})", message); 21 | 22 | if (message instanceof Sum) { 23 | log.info("got a Sum message"); 24 | Sum sum = (Sum) message; 25 | 26 | int result = sum.getFirst() + sum.getSecond(); 27 | getSender().tell(new Result(result), getSelf()); 28 | System.out.println("sub over"); 29 | 30 | // loggingActor.tell(sum.getFirst() + " + " + sum.getSecond() + " = " + result, 31 | // getSelf()); 32 | } else { 33 | unhandled(message); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/src/main/resources/beans-annotation2.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 23 | 24 | -------------------------------------------------------------------------------- /async-program-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | com.jiaduo.async.demo 6 | async-program-demo 7 | 0.0.1-SNAPSHOT 8 | pom 9 | 10 | async-program-demo 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | junit 20 | junit 21 | 3.8.1 22 | test 23 | 24 | 25 | 26 | First-Chapter 27 | Second-Chapter 28 | Third-Chapter 29 | ChapterIV 30 | Chapter5 31 | Chapter8 32 | 33 | -------------------------------------------------------------------------------- /async-program-demo/Second-Chapter/src/main/java/org/Second/Chapter/Thread/AsyncThreadExample.java: -------------------------------------------------------------------------------- 1 | package org.Second.Chapter.Thread; 2 | 3 | /** 4 | * Hello world! 5 | * 6 | */ 7 | public class AsyncThreadExample { 8 | 9 | public static void doSomethingA() { 10 | 11 | try { 12 | Thread.sleep(2000); 13 | } catch (InterruptedException e) { 14 | e.printStackTrace(); 15 | } 16 | System.out.println("--- doSomethingA---"); 17 | } 18 | 19 | public static void doSomethingB() { 20 | try { 21 | Thread.sleep(2000); 22 | } catch (InterruptedException e) { 23 | e.printStackTrace(); 24 | } 25 | System.out.println("--- doSomethingB---"); 26 | 27 | } 28 | 29 | public static void main(String[] args) throws InterruptedException { 30 | 31 | long start = System.currentTimeMillis(); 32 | 33 | // 1.开启异步单元执行任务A 34 | Thread thread = new Thread(() -> { 35 | try { 36 | doSomethingA(); 37 | 38 | } catch (Exception e) { 39 | e.printStackTrace(); 40 | } 41 | }, "threadA"); 42 | thread.start(); 43 | 44 | // 2.执行任务B 45 | doSomethingB(); 46 | 47 | // 3.同步等待线程A运行结束 48 | thread.join(); 49 | System.out.println(System.currentTimeMillis() - start); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Shared/Shared.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/src/main/resources/beans-annotation3.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | 15 | 16 | 18 | 19 | 21 | 23 | 24 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Client/src/main/java/example/akka/remote/client/CalculatorActor.java: -------------------------------------------------------------------------------- 1 | package example.akka.remote.client; 2 | 3 | import akka.actor.ActorRef; 4 | import akka.actor.Props; 5 | import akka.actor.UntypedActor; 6 | import akka.event.Logging; 7 | import akka.event.LoggingAdapter; 8 | import example.akka.remote.shared.LoggingActor; 9 | 10 | import static example.akka.remote.shared.Messages.*; 11 | 12 | public class CalculatorActor extends UntypedActor { 13 | 14 | private LoggingAdapter log = Logging.getLogger(getContext().system(), this); 15 | 16 | // private ActorRef loggingActor = 17 | // getContext().actorOf(Props.create(LoggingActor.class), "LoggingActor"); 18 | 19 | @Override 20 | public void onReceive(Object message) throws Exception { 21 | log.info("onReceive({})", message); 22 | 23 | if (message instanceof Sum) { 24 | log.info("got a Sum message"); 25 | Sum sum = (Sum) message; 26 | 27 | int result = sum.getFirst() + sum.getSecond(); 28 | getSender().tell(new Result(result), getSelf()); 29 | System.out.println("sub over"); 30 | 31 | // loggingActor.tell(sum.getFirst() + " + " + sum.getSecond() + " = " + result, 32 | // getSelf()); 33 | } else { 34 | unhandled(message); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Client/Client.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Server/Server.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /async-program-demo/Second-Chapter/src/main/java/org/Second/Chapter/Thread/AsyncThreadExample2.java: -------------------------------------------------------------------------------- 1 | package org.Second.Chapter.Thread; 2 | 3 | /** 4 | * Hello world! 5 | * 6 | */ 7 | public class AsyncThreadExample2 { 8 | 9 | public static void doSomethingA() { 10 | 11 | try { 12 | Thread.sleep(2000); 13 | } catch (InterruptedException e) { 14 | e.printStackTrace(); 15 | } 16 | System.out.println("--- doSomethingA---"); 17 | } 18 | 19 | public static void doSomethingB() { 20 | try { 21 | Thread.sleep(2000); 22 | } catch (InterruptedException e) { 23 | e.printStackTrace(); 24 | } 25 | System.out.println("--- doSomethingB---"); 26 | 27 | } 28 | 29 | public static void main(String[] args) throws InterruptedException { 30 | long start = System.currentTimeMillis(); 31 | // 1.开启异步单元执行任务A 32 | Thread thread = new Thread("threadA") { 33 | @Override 34 | public void run() { 35 | try { 36 | doSomethingA(); 37 | 38 | } catch (Exception e) { 39 | e.printStackTrace(); 40 | } 41 | } 42 | }; 43 | 44 | //thread.setDaemon(true); 45 | thread.start(); 46 | 47 | // 2.执行任务B 48 | doSomethingB(); 49 | 50 | // 3.同步等待线程A运行结束 51 | thread.join(); 52 | System.out.println(System.currentTimeMillis() - start); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/akka/ClientActor.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.akka; 2 | 3 | import akka.actor.ActorRef; 4 | import akka.actor.ActorSelection; 5 | import akka.actor.Props; 6 | import akka.actor.UntypedActor; 7 | import akka.event.Logging; 8 | import akka.event.LoggingAdapter; 9 | 10 | public class ClientActor extends UntypedActor { 11 | private LoggingAdapter log = Logging.getLogger(getContext().system(), this); 12 | 13 | private ActorSelection actorRef = getContext() 14 | .actorSelection("akka.tcp://AkkaRemoteServer@127.0.0.1:2552/user/CalculatorActor"); 15 | 16 | // private ActorRef actorRef = 17 | // getContext().actorOf(Props.create(CalculatorActor.class), "calculatorActor"); 18 | 19 | @Override 20 | public void onReceive(Object message) throws Exception { 21 | if (message.equals("DoCalcs")) { 22 | 23 | // log.info("Got a calc job, send it to the remote calculator"); 24 | log.info("Got a calc job, local calculator"); 25 | 26 | System.out.println(actorRef); 27 | actorRef.tell(new Messages.Sum(1, 2), getSelf()); 28 | 29 | } else if (message instanceof Messages.Result) { 30 | Messages.Result result = (Messages.Result) message; 31 | log.info("Got result back from calculator: {}", result.getResult()); 32 | } 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/src/main/java/org/Chapter5/reactor/AsyncRpcCall.java: -------------------------------------------------------------------------------- 1 | package org.Chapter5.reactor; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.function.Consumer; 6 | import reactor.core.publisher.Flux; 7 | import reactor.core.scheduler.Schedulers; 8 | 9 | public class AsyncRpcCall { 10 | 11 | public static String rpcCall(String ip, String param) { 12 | 13 | System.out.println(ip + " rpcCall:" + param); 14 | try { 15 | Thread.sleep(2000); 16 | } catch (InterruptedException e) { 17 | // TODO Auto-generated catch block 18 | e.printStackTrace(); 19 | } 20 | 21 | return param; 22 | 23 | } 24 | 25 | public static void main(String[] args) throws InterruptedException { 26 | 27 | // 1.生成ip列表 28 | List ipList = new ArrayList(); 29 | for (int i = 1; i <= 10; ++i) { 30 | ipList.add("192.168.0." + i); 31 | } 32 | 33 | // 2.并发调用 34 | Flux.fromArray(ipList.toArray(new String[0])).flatMap(ip -> // 2.1 35 | Flux.just(ip)// 2.2 36 | .subscribeOn(Schedulers.elastic())// 2.3 37 | .map(v -> rpcCall(v, v)))// 2.4 38 | .subscribe(new Consumer() { 39 | 40 | @Override 41 | public void accept(String t) { 42 | 43 | } 44 | }); 45 | 46 | Thread.sleep(3000); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/src/main/java/org/ChapterIV/TaskExecutor/AsyncExecutorExample.java: -------------------------------------------------------------------------------- 1 | package org.ChapterIV.TaskExecutor; 2 | 3 | import org.springframework.core.task.TaskExecutor; 4 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 5 | 6 | public class AsyncExecutorExample { 7 | private class MessagePrinterTask implements Runnable { 8 | 9 | private String message; 10 | 11 | public MessagePrinterTask(String message) { 12 | this.message = message; 13 | } 14 | 15 | public void run() { 16 | try { 17 | Thread.sleep(1000); 18 | System.out.println(Thread.currentThread().getName() + " " + message); 19 | } catch (Exception e) { 20 | e.printStackTrace(); 21 | } 22 | } 23 | } 24 | 25 | public TaskExecutor getTaskExecutor() { 26 | return taskExecutor; 27 | } 28 | 29 | public void setTaskExecutor(TaskExecutor taskExecutor) { 30 | this.taskExecutor = taskExecutor; 31 | } 32 | 33 | // 线程池执行器 34 | private TaskExecutor taskExecutor; 35 | 36 | public void shutdown() { 37 | if (taskExecutor instanceof ThreadPoolTaskExecutor) { 38 | ((ThreadPoolTaskExecutor) taskExecutor).shutdown(); 39 | } 40 | } 41 | 42 | public void printMessages() { 43 | for (int i = 0; i < 6; i++) { 44 | taskExecutor.execute(new MessagePrinterTask("Message" + i)); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /dubbo-demo/Consumer/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Client/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Server/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /async-program-demo/Second-Chapter/src/main/java/org/Second/Chapter/ThreadPool/AsyncThreadPoolExample3.java: -------------------------------------------------------------------------------- 1 | package org.Second.Chapter.ThreadPool; 2 | 3 | import java.util.concurrent.ExecutionException; 4 | import java.util.concurrent.Future; 5 | import java.util.concurrent.LinkedBlockingQueue; 6 | import java.util.concurrent.ThreadPoolExecutor; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | public class AsyncThreadPoolExample3 { 10 | 11 | public static String doSomethingA() { 12 | 13 | try { 14 | Thread.sleep(2000); 15 | } catch (InterruptedException e) { 16 | e.printStackTrace(); 17 | } 18 | System.out.println("--- doSomethingA---"); 19 | return "A Task Done"; 20 | } 21 | 22 | // 0自定义线程池 23 | private final static int AVALIABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); 24 | private final static ThreadPoolExecutor POOL_EXECUTOR = new ThreadPoolExecutor(AVALIABLE_PROCESSORS, 25 | AVALIABLE_PROCESSORS * 2, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(5), 26 | new NamedThreadFactory("ASYNC-POOL"), new ThreadPoolExecutor.CallerRunsPolicy()); 27 | 28 | public static void main(String[] args) throws InterruptedException, ExecutionException { 29 | 30 | // 1.开启异步单元执行任务A 31 | Future resultA = POOL_EXECUTOR.submit(() -> doSomethingA()); 32 | 33 | // 2.同步等待执行结果 34 | System.out.println(resultA.get()); 35 | } 36 | } -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/netty/NettyClientHandler.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.netty; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | 5 | import io.netty.channel.ChannelHandler; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.channel.ChannelInboundHandlerAdapter; 8 | import io.netty.channel.ChannelHandler.Sharable; 9 | import io.netty.util.concurrent.Future; 10 | 11 | @Sharable 12 | public class NettyClientHandler extends ChannelInboundHandlerAdapter { 13 | 14 | @Override 15 | public void channelActive(ChannelHandlerContext ctx) { 16 | 17 | System.out.println("--- client already connected----"); 18 | 19 | } 20 | 21 | @Override 22 | public void channelRead(ChannelHandlerContext ctx, Object msg) { 23 | 24 | // 提交给线程池异步执行, 释放IO线程 25 | AllChannelHandler.channelRead(() -> { 26 | // 1.根据请求id,获取对应future 27 | CompletableFuture future = FutureMapUtil.remove(((String) msg).split(":")[1]); 28 | // 2.如果存在,则设置future结果 29 | if (null != future) { 30 | future.complete(((String) msg).split(":")[0]); 31 | } 32 | }); 33 | 34 | } 35 | 36 | @Override 37 | public void channelReadComplete(ChannelHandlerContext ctx) { 38 | } 39 | 40 | @Override 41 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 42 | cause.printStackTrace(); 43 | ctx.close(); 44 | } 45 | } -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/src/main/java/org/ChapterIV/Async/TestaskExecutor.java: -------------------------------------------------------------------------------- 1 | package org.ChapterIV.Async; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.function.BiConsumer; 5 | 6 | import org.springframework.context.support.ClassPathXmlApplicationContext; 7 | 8 | public class TestaskExecutor { 9 | 10 | public static void main(String arg[]) throws InterruptedException { 11 | // 1.创建容器上下文 12 | ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext( 13 | new String[] { "beans-annotation.xml" }); 14 | 15 | // 2. 获取AsyncExecutorExample实例并调用打印方法 16 | System.out.println(Thread.currentThread().getName() + " begin "); 17 | AsyncAnnotationExample asyncCommentExample = applicationContext.getBean(AsyncAnnotationExample.class); 18 | 19 | // 3.获取异步future并设置回调 20 | CompletableFuture resultFuture = asyncCommentExample.doSomething(); 21 | resultFuture.whenComplete(new BiConsumer() { 22 | @Override 23 | public void accept(String t, Throwable u) { 24 | if (null == u) { 25 | System.out.println(Thread.currentThread().getName() + " " + t); 26 | } else { 27 | System.out.println("error:" + u.getLocalizedMessage()); 28 | } 29 | 30 | } 31 | }); 32 | 33 | System.out.println(Thread.currentThread().getName() + " end "); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /async-program-demo/Second-Chapter/src/main/java/org/Second/Chapter/ThreadPool/NamedThreadFactory.java: -------------------------------------------------------------------------------- 1 | package org.Second.Chapter.ThreadPool; 2 | 3 | import java.util.concurrent.ThreadFactory; 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | 6 | public class NamedThreadFactory implements ThreadFactory { 7 | 8 | private static final AtomicInteger poolNumber = new AtomicInteger(1); 9 | 10 | private final AtomicInteger threadNumber = new AtomicInteger(1); 11 | private final ThreadGroup group; 12 | private final String namePrefix; 13 | private final boolean isDaemon; 14 | 15 | public NamedThreadFactory() { 16 | this("pool"); 17 | } 18 | 19 | public NamedThreadFactory(String name) { 20 | this(name, true); 21 | } 22 | 23 | public NamedThreadFactory(String preffix, boolean daemon) { 24 | SecurityManager s = System.getSecurityManager(); 25 | group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); 26 | namePrefix = preffix + "-" + poolNumber.getAndIncrement() + "-thread-"; 27 | isDaemon = daemon; 28 | } 29 | 30 | public Thread newThread(Runnable r) { 31 | Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); 32 | t.setDaemon(isDaemon); 33 | if (t.getPriority() != Thread.NORM_PRIORITY) { 34 | t.setPriority(Thread.NORM_PRIORITY); 35 | } 36 | return t; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/metaq/ProducerSync.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.metaq; 2 | 3 | import org.apache.rocketmq.client.exception.MQClientException; 4 | import org.apache.rocketmq.client.producer.DefaultMQProducer; 5 | import org.apache.rocketmq.client.producer.SendResult; 6 | import org.apache.rocketmq.common.message.Message; 7 | import org.apache.rocketmq.remoting.common.RemotingHelper; 8 | 9 | public class ProducerSync { 10 | public static void main(String[] args) throws MQClientException, InterruptedException { 11 | 12 | // 1. 创建生产者实例 13 | DefaultMQProducer producer = new DefaultMQProducer("my-producer-group"); 14 | // 2. 设置nameserver地址,多个可以使用;分隔 15 | producer.setNamesrvAddr("127.0.0.1:9876"); 16 | // 3. 启动生产者 17 | producer.start(); 18 | 19 | // 4. 发送消息 20 | for (int i = 0; i < 3; i++) { 21 | try { 22 | 23 | // 4.1 创建消息体,topic为TopicTest,tag为TagA 24 | Message msg = new Message("TopicTest" /* Topic */, "TagA" /* Tag */, 25 | ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */ 26 | ); 27 | 28 | // 4.2 发送消息 29 | SendResult sendResult = producer.send(msg); 30 | // 4.3 31 | System.out.printf("%s%n", sendResult); 32 | } catch (Exception e) { 33 | e.printStackTrace(); 34 | } 35 | } 36 | 37 | // 5. 关闭 38 | producer.shutdown(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/CompletableFuture/TestFutureException2.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter.CompletableFuture; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ExecutionException; 5 | import java.util.concurrent.TimeUnit; 6 | import java.util.concurrent.TimeoutException; 7 | import java.util.function.Supplier; 8 | 9 | // // 10 | 11 | public class TestFutureException2 { 12 | 13 | public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException { 14 | // 1.创建一个CompletableFuture对象 15 | CompletableFuture future = new CompletableFuture(); 16 | 17 | // 2.开启线程计算任务结果,并设置 18 | new Thread(() -> { 19 | 20 | // 2.1休眠3s,模拟任务计算 21 | try { 22 | // 2.1.1 抛出异常 23 | if (true) { 24 | throw new RuntimeException("excetion test"); 25 | } 26 | // 2.1.2设置正常结果 27 | future.complete("ok"); 28 | } catch (Exception e) { 29 | // 2.1.3 设置异常结果 30 | future.completeExceptionally(e); 31 | } 32 | // 2.2设置计算结果到future 33 | System.out.println("----" + Thread.currentThread().getName() + " set future result----"); 34 | 35 | }, "thread-1").start(); 36 | 37 | // 3.等待计算结果 38 | // System.out.println(future.get()); 39 | System.out.println(future.exceptionally(t -> "default").get());// 默认值 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /java-akka-remote-demo/Client/src/main/java/example/akka/remote/client/ClientActor.java: -------------------------------------------------------------------------------- 1 | package example.akka.remote.client; 2 | 3 | import akka.actor.ActorRef; 4 | import akka.actor.ActorSelection; 5 | import akka.actor.Props; 6 | import akka.actor.UntypedActor; 7 | import akka.event.Logging; 8 | import akka.event.LoggingAdapter; 9 | import example.akka.remote.shared.Messages; 10 | 11 | public class ClientActor extends UntypedActor { 12 | private LoggingAdapter log = Logging.getLogger(getContext().system(), this); 13 | 14 | private ActorSelection actorRef = getContext() 15 | .actorSelection("akka.tcp://AkkaRemoteServer@127.0.0.1:2552/user/CalculatorActor"); 16 | 17 | // private ActorRef actorRef = 18 | // getContext().actorOf(Props.create(CalculatorActor.class), "calculatorActor"); 19 | 20 | @Override 21 | public void onReceive(Object message) throws Exception { 22 | if (message.equals("DoCalcs")) { 23 | 24 | // log.info("Got a calc job, send it to the remote calculator"); 25 | log.info("Got a calc job, local calculator"); 26 | 27 | System.out.println(actorRef); 28 | actorRef.tell(new Messages.Sum(1, 2), getSelf()); 29 | 30 | } else if (message instanceof Messages.Result) { 31 | Messages.Result result = (Messages.Result) message; 32 | log.info("Got result back from calculator: {}", result.getResult()); 33 | } 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/src/main/java/org/Chapter5/rxjava/AsyncRpcCall3.java: -------------------------------------------------------------------------------- 1 | package org.Chapter5.rxjava; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.CompletableFuture; 6 | import java.util.stream.Collectors; 7 | 8 | import io.reactivex.Flowable; 9 | import io.reactivex.functions.Consumer; 10 | import io.reactivex.schedulers.Schedulers; 11 | 12 | public class AsyncRpcCall3 { 13 | 14 | public static String rpcCall(String ip, String param) { 15 | 16 | System.out.println(ip + " rpcCall:" + param); 17 | try { 18 | Thread.sleep(2000); 19 | } catch (InterruptedException e) { 20 | // TODO Auto-generated catch block 21 | e.printStackTrace(); 22 | } 23 | 24 | return param; 25 | 26 | } 27 | 28 | public static void main(String[] args) { 29 | 30 | // 1.生成ip列表 31 | List ipList = new ArrayList(); 32 | for (int i = 1; i <= 10; ++i) { 33 | ipList.add("192.168.0." + i); 34 | } 35 | 36 | // 2.并发调用 37 | long start = System.currentTimeMillis(); 38 | 39 | Flowable.fromArray( ipList.toArray(new String[0])) 40 | .parallel() 41 | .runOn(Schedulers.io()) 42 | .map(v -> rpcCall(v, v)) 43 | .sequential() 44 | .blockingSubscribe(System.out::println);//2.5 45 | 46 | //3.打印耗时 47 | System.out.println("cost:" + (System.currentTimeMillis() - start)); 48 | 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /dubbo-demo/Consumer/src/main/java/org/apache/dubbo/demo/consumer/APiAsyncConsumer.java: -------------------------------------------------------------------------------- 1 | package org.apache.dubbo.demo.consumer; 2 | 3 | import java.util.concurrent.ExecutionException; 4 | 5 | import org.apache.dubbo.config.ApplicationConfig; 6 | import org.apache.dubbo.config.ReferenceConfig; 7 | import org.apache.dubbo.config.RegistryConfig; 8 | import org.apache.dubbo.rpc.RpcContext; 9 | 10 | import com.books.dubbo.demo.api.GreetingService; 11 | 12 | public class APiAsyncConsumer { 13 | public static void main(String[] args) throws InterruptedException, ExecutionException { 14 | //1.创建引用实例,并设置属性 15 | ReferenceConfig referenceConfig = new ReferenceConfig(); 16 | referenceConfig.setApplication(new ApplicationConfig("first-dubbo-consumer")); 17 | referenceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); 18 | referenceConfig.setInterface(GreetingService.class); 19 | referenceConfig.setVersion("1.0.0"); 20 | referenceConfig.setGroup("dubbo"); 21 | 22 | //2. 设置为异步 23 | referenceConfig.setAsync(true); 24 | 25 | // 3.引用服务 26 | GreetingService greetingService = referenceConfig.get(); 27 | 28 | 29 | System.out.println(greetingService.sayHello("world")); 30 | 31 | //4.等待结果 32 | java.util.concurrent.Future future = RpcContext.getContext().getFuture(); 33 | System.out.println(future.get()); 34 | 35 | } 36 | } -------------------------------------------------------------------------------- /async-program-demo/Chapter5/src/main/java/org/Chapter5/rxjava/AsyncRpcCall4.java: -------------------------------------------------------------------------------- 1 | package org.Chapter5.rxjava; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.CompletableFuture; 6 | import java.util.stream.Collectors; 7 | 8 | import io.reactivex.Flowable; 9 | import io.reactivex.functions.Consumer; 10 | import io.reactivex.schedulers.Schedulers; 11 | 12 | // 13 | 14 | public class AsyncRpcCall4 { 15 | 16 | public static String rpcCall(String ip, String param) { 17 | 18 | System.out.println(Thread.currentThread().getName() + " " + ip + " rpcCall:" + param); 19 | try { 20 | Thread.sleep(2000); 21 | } catch (InterruptedException e) { 22 | // TODO Auto-generated catch block 23 | e.printStackTrace(); 24 | } 25 | 26 | return param; 27 | 28 | } 29 | 30 | public static void main(String[] args) throws InterruptedException { 31 | 32 | // 1.生成ip列表 33 | List ipList = new ArrayList(); 34 | for (int i = 1; i <= 10; ++i) { 35 | ipList.add("192.168.0." + i); 36 | } 37 | 38 | // 2.顺序调用 39 | Flowable.fromArray(ipList.toArray(new String[0])).observeOn(Schedulers.io())// 2.1切换到IO线程执行 40 | .map(v -> rpcCall(v, v))// 2.2映射结果 41 | .subscribe(System.out::println);// 2.3订阅 42 | 43 | //3. 44 | System.out.println("main execute over and wait"); 45 | Thread.currentThread().join();// 挂起main函数所在线程 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/metaq/Producer.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.metaq; 2 | 3 | import org.apache.rocketmq.client.exception.MQClientException; 4 | import org.apache.rocketmq.client.producer.DefaultMQProducer; 5 | import org.apache.rocketmq.client.producer.SendResult; 6 | import org.apache.rocketmq.common.message.Message; 7 | import org.apache.rocketmq.remoting.common.RemotingHelper; 8 | 9 | public class Producer { 10 | public static void main(String[] args) throws MQClientException, InterruptedException { 11 | 12 | // 1. 创建生产者实例 13 | DefaultMQProducer producer = new DefaultMQProducer("jiaduo-producer-group"); 14 | // 2. 设置nameserver地址,多个可以使用;分隔 15 | producer.setNamesrvAddr("127.0.0.1:9876"); 16 | producer.setSendMsgTimeout(1000); 17 | // 3. 启动生产者 18 | producer.start(); 19 | 20 | // 4. 发送消息 21 | for (int i = 0; i < 10; i++) { 22 | try { 23 | 24 | // 4.1 创建消息体,topic为TopicTest,tag为TagA 25 | Message msg = new Message("TopicTest" /* Topic */, "TagA" /* Tag */, 26 | ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */ 27 | ); 28 | 29 | // 4.2 发送消息 30 | SendResult sendResult = producer.send(msg); 31 | // 4.3 32 | System.out.printf("%s%n", sendResult); 33 | } catch (Exception e) { 34 | e.printStackTrace(); 35 | } 36 | } 37 | 38 | // 5. 关闭 39 | producer.shutdown(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/src/main/java/com/books/dubbo/demo/provider/ApiProviderForAsync.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.provider; 2 | 3 | import java.io.IOException; 4 | import java.util.HashMap; 5 | 6 | import org.apache.dubbo.config.ApplicationConfig; 7 | import org.apache.dubbo.config.RegistryConfig; 8 | import org.apache.dubbo.config.ServiceConfig; 9 | 10 | import com.books.dubbo.demo.api.GreetingService; 11 | import com.books.dubbo.demo.api.GrettingServiceAsync; 12 | 13 | public class ApiProviderForAsync { 14 | 15 | public static void main(String[] args) throws IOException { 16 | 17 | // 1.创建服务发布实例,并设置 18 | ServiceConfig serviceConfig = new ServiceConfig(); 19 | serviceConfig.setApplication(new ApplicationConfig("first-dubbo-provider")); 20 | serviceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); 21 | serviceConfig.setInterface(GrettingServiceAsync.class); 22 | serviceConfig.setRef(new GrettingServiceAsyncImpl()); 23 | serviceConfig.setVersion("1.0.0"); 24 | serviceConfig.setGroup("dubbo"); 25 | 26 | // 2.设置线程池策略 27 | // HashMap parameters = new HashMap<>(); 28 | // parameters.put("threadpool", "mythreadpool"); 29 | // serviceConfig.setParameters(parameters); 30 | 31 | // 3.导出服务 32 | serviceConfig.export(); 33 | 34 | // 4.阻塞线程 35 | System.out.println("server is started"); 36 | System.in.read(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/src/main/java/org/Chapter5/rxjava/AsyncRpcCallromFuture.java: -------------------------------------------------------------------------------- 1 | package org.Chapter5.rxjava; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.CompletableFuture; 6 | import java.util.stream.Collectors; 7 | 8 | import io.reactivex.Flowable; 9 | import io.reactivex.functions.Consumer; 10 | import io.reactivex.schedulers.Schedulers; 11 | 12 | public class AsyncRpcCallromFuture { 13 | 14 | public static String rpcCall(String ip, String param) { 15 | 16 | System.out.println(ip + " rpcCall:" + param); 17 | try { 18 | Thread.sleep(2000); 19 | } catch (InterruptedException e) { 20 | // TODO Auto-generated catch block 21 | e.printStackTrace(); 22 | } 23 | 24 | return param; 25 | 26 | } 27 | 28 | public static void main(String[] args) { 29 | 30 | // 1.生成ip列表 31 | List ipList = new ArrayList(); 32 | for (int i = 1; i <= 10; ++i) { 33 | ipList.add("192.168.0." + i); 34 | } 35 | 36 | // 2.并发调用 37 | long start = System.currentTimeMillis(); 38 | Flowable.fromArray( ipList.toArray(new String[0])) 39 | .flatMap(ip -> //2.1 40 | Flowable.just(ip)//2.2 41 | .subscribeOn(Schedulers.io())//2.3 42 | .map(v -> rpcCall(v, v)))//2.4 43 | .blockingSubscribe(System.out::println);//2.5 44 | 45 | //3.打印耗时 46 | System.out.println("cost:" + (System.currentTimeMillis() - start)); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/disruptor/LongEventMain.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.disruptor; 2 | 3 | import com.lmax.disruptor.dsl.Disruptor; 4 | import com.lmax.disruptor.dsl.ProducerType; 5 | import com.lmax.disruptor.BlockingWaitStrategy; 6 | import com.lmax.disruptor.RingBuffer; 7 | import com.lmax.disruptor.util.DaemonThreadFactory; 8 | 9 | public class LongEventMain { 10 | 11 | public static void main(String[] args) throws Exception { 12 | // 1.创建Ring Buffer中事件元素的工厂对象 13 | LongEventFactory factory = new LongEventFactory(); 14 | 15 | // 2.指定Ring Buffer的大小,必须为2的幂次方. 16 | int bufferSize = 1024; 17 | 18 | // 3.构造Disruptor 19 | Disruptor disruptor = new Disruptor(factory, bufferSize, DaemonThreadFactory.INSTANCE, ProducerType.SINGLE,new BlockingWaitStrategy()); 20 | 21 | // 4.注册消费者 22 | disruptor.handleEventsWith(new JournalConsumer(), new ReplicationConsumer()).then(new ApplicationConsumer()); 23 | 24 | // 5.启动Disruptor, 启动线程运行 25 | disruptor.start(); 26 | 27 | // 6.从Disruptor中获取Ring Buffer。 28 | RingBuffer ringBuffer = disruptor.getRingBuffer(); 29 | 30 | // 7. 创建生产者 31 | LongEventProducer producer = new LongEventProducer(ringBuffer); 32 | 33 | // 8. 生产元素,并放入RingBuffer 34 | for (long l = 0; l < 100; l++) { 35 | producer.onData(l); 36 | 37 | Thread.sleep(1000); 38 | } 39 | 40 | // 9.挂起当前线程 41 | Thread.currentThread().join(); 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /dubbo-demo/Provider/src/main/java/com/books/dubbo/demo/provider/ApiProvider.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.provider; 2 | 3 | import java.io.IOException; 4 | 5 | import org.apache.dubbo.config.ApplicationConfig; 6 | import org.apache.dubbo.config.RegistryConfig; 7 | import org.apache.dubbo.config.ServiceConfig; 8 | 9 | import com.books.dubbo.demo.api.GreetingService; 10 | 11 | public class ApiProvider { 12 | 13 | public static void main(String[] args) throws IOException { 14 | // 1.创建ServiceConfig实例 15 | ServiceConfig serviceConfig = new ServiceConfig(); 16 | // 2.设置应用程序配置 17 | serviceConfig.setApplication(new ApplicationConfig("first-dubbo-provider")); 18 | 19 | // 3.设置服务注册中心信息 20 | RegistryConfig registryConfig = new RegistryConfig("zookeeper://127.0.0.1:2181"); 21 | serviceConfig.setRegistry(registryConfig); 22 | // 4.设置接口与实现类 23 | serviceConfig.setInterface(GreetingService.class); 24 | serviceConfig.setRef(new GreetingServiceImpl()); 25 | 26 | // 5.设置服务分组与版本 27 | serviceConfig.setVersion("1.0.0"); 28 | serviceConfig.setGroup("dubbo"); 29 | 30 | // 6.设置线程池策略 31 | // HashMap parameters = new HashMap<>(); 32 | // parameters.put("threadpool", "mythreadpool"); 33 | // serviceConfig.setParameters(parameters); 34 | 35 | // 7.导出服务 36 | serviceConfig.export(); 37 | 38 | // 8.挂起线程,避免服务停止 39 | System.out.println("server is started"); 40 | System.in.read(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/src/main/java/com/books/dubbo/demo/provider/ApiProviderForAsyncContext.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.provider; 2 | 3 | import java.io.IOException; 4 | import java.util.HashMap; 5 | 6 | import org.apache.dubbo.config.ApplicationConfig; 7 | import org.apache.dubbo.config.RegistryConfig; 8 | import org.apache.dubbo.config.ServiceConfig; 9 | 10 | import com.books.dubbo.demo.api.GreetingService; 11 | import com.books.dubbo.demo.api.GrettingServiceAsync; 12 | import com.books.dubbo.demo.api.GrettingServiceRpcContext; 13 | 14 | public class ApiProviderForAsyncContext { 15 | 16 | public static void main(String[] args) throws IOException { 17 | 18 | ServiceConfig serviceConfig = new ServiceConfig(); 19 | serviceConfig.setApplication(new ApplicationConfig("first-dubbo-provider")); 20 | serviceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); 21 | serviceConfig.setInterface(GrettingServiceRpcContext.class); 22 | serviceConfig.setRef(new GrettingServiceAsyncContextImpl()); 23 | 24 | serviceConfig.setVersion("1.0.0"); 25 | serviceConfig.setGroup("dubbo"); 26 | 27 | //设置线程池策略 28 | HashMap parameters = new HashMap<>(); 29 | parameters.put("threadpool", "mythreadpool"); 30 | serviceConfig.setParameters(parameters); 31 | 32 | serviceConfig.export(); 33 | 34 | System.out.println("server is started"); 35 | System.in.read(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/src/main/java/org/Chapter5/rxjava/AsyncRpcCall.java: -------------------------------------------------------------------------------- 1 | package org.Chapter5.rxjava; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.Callable; 6 | import java.util.concurrent.CompletableFuture; 7 | import java.util.function.Supplier; 8 | import java.util.stream.Collectors; 9 | 10 | import io.reactivex.Flowable; 11 | import io.reactivex.functions.Consumer; 12 | import io.reactivex.schedulers.Schedulers; 13 | 14 | public class AsyncRpcCall { 15 | 16 | public static String rpcCall(String ip, String param) { 17 | 18 | System.out.println(ip + " rpcCall:" + param); 19 | try { 20 | Thread.sleep(2000); 21 | } catch (InterruptedException e) { 22 | // TODO Auto-generated catch block 23 | e.printStackTrace(); 24 | } 25 | 26 | return param; 27 | 28 | } 29 | 30 | public static void main(String[] args) throws InterruptedException { 31 | 32 | CompletableFuture future = CompletableFuture.supplyAsync(new Supplier() { 33 | 34 | @Override 35 | public String get() { 36 | try { 37 | Thread.sleep(3000); 38 | } catch (InterruptedException e) { 39 | // TODO Auto-generated catch block 40 | e.printStackTrace(); 41 | } 42 | return "test"; 43 | } 44 | }); 45 | 46 | Flowable.fromCallable(()->future.get()).subscribeOn(Schedulers.io()).subscribe(System.out::println); 47 | System.out.println(111); 48 | 49 | Thread.sleep(3000); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/CompletableFuture/StreamTestFuture2.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter.CompletableFuture; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Random; 6 | import java.util.concurrent.CompletableFuture; 7 | import java.util.stream.Collector; 8 | import java.util.stream.Collectors; 9 | 10 | public class StreamTestFuture2 { 11 | 12 | public static String rpcCall(String ip, String param) { 13 | 14 | System.out.println(ip + " rpcCall:" + param); 15 | try { 16 | Thread.sleep(1000); 17 | } catch (InterruptedException e) { 18 | // TODO Auto-generated catch block 19 | e.printStackTrace(); 20 | } 21 | 22 | return param; 23 | 24 | } 25 | 26 | public static void main(String[] args) { 27 | 28 | // 1.生成ip列表 29 | List ipList = new ArrayList(); 30 | for (int i = 1; i <= 10; ++i) { 31 | ipList.add("192.168.0." + i); 32 | } 33 | 34 | // 2.并发调用 35 | long start = System.currentTimeMillis(); 36 | List> futureList = ipList.stream() 37 | .map(ip -> CompletableFuture.supplyAsync(() -> rpcCall(ip, ip))).collect(Collectors.toList()); 38 | 39 | List resultList = futureList.stream().map(future -> future.join()).collect(Collectors.toList()); 40 | 41 | // 3.输出 42 | resultList.stream().forEach(r -> System.out.println(r)); 43 | 44 | System.out.println("cost:" + (System.currentTimeMillis() - start)); 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /dubbo-demo/Consumer/src/main/java/org/apache/dubbo/demo/consumer/APiConsumerForProviderAsyncContext.java: -------------------------------------------------------------------------------- 1 | package org.apache.dubbo.demo.consumer; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | 5 | import org.apache.dubbo.config.ApplicationConfig; 6 | import org.apache.dubbo.config.ReferenceConfig; 7 | import org.apache.dubbo.config.RegistryConfig; 8 | import org.apache.dubbo.rpc.RpcContext; 9 | 10 | import com.books.dubbo.demo.api.GreetingService; 11 | import com.books.dubbo.demo.api.GrettingServiceAsync; 12 | import com.books.dubbo.demo.api.GrettingServiceRpcContext; 13 | 14 | public class APiConsumerForProviderAsyncContext { 15 | public static void main(String[] args) throws InterruptedException { 16 | ReferenceConfig referenceConfig = new ReferenceConfig(); 17 | referenceConfig.setApplication(new ApplicationConfig("first-dubbo-consumer")); 18 | referenceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); 19 | referenceConfig.setInterface(GrettingServiceRpcContext.class); 20 | referenceConfig.setTimeout(5000); 21 | 22 | referenceConfig.setVersion("1.0.0"); 23 | referenceConfig.setGroup("dubbo"); 24 | 25 | GrettingServiceRpcContext greetingService = referenceConfig.get(); 26 | 27 | //设置隐士参数 28 | RpcContext.getContext().setAttachment("company", "alibaba"); 29 | String result = greetingService.sayHello("world"); 30 | System.out.println(result); 31 | 32 | 33 | } 34 | } -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/CompletableFuture/TestCompletableFutureCallBack.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter.CompletableFuture; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ExecutionException; 5 | import java.util.function.Function; 6 | import java.util.function.Supplier; 7 | 8 | public class TestCompletableFutureCallBack { 9 | 10 | public static void main(String[] args) throws InterruptedException, ExecutionException { 11 | 12 | // 1.创建异步任务,并返回future 13 | CompletableFuture oneFuture = CompletableFuture.supplyAsync(new Supplier() { 14 | 15 | @Override 16 | public String get() { 17 | 18 | // 1.1休眠2s,模拟任务计算 19 | try { 20 | Thread.sleep(2000); 21 | } catch (InterruptedException e) { 22 | e.printStackTrace(); 23 | } 24 | // 1.2返回计算结果 25 | return "hello"; 26 | } 27 | }); 28 | // 2.在future上施加事件,当future计算完成后回调该事件,并返回新future 29 | CompletableFuture twoFuture = oneFuture.thenApply(new Function() { 30 | 31 | // 2.1对步骤1计算结果基础上进行计算,这里t为步骤1返回的hello 32 | @Override 33 | public String apply(String t) { 34 | // 2.1.1对oneFuture返回的结果进行加工 35 | try { 36 | Thread.sleep(1000); 37 | } catch (Exception e) { 38 | e.printStackTrace(); 39 | } 40 | // 2.1.2返回加工后结果 41 | return t + " jiduo"; 42 | } 43 | }); 44 | 45 | // 3.同步等待twoFuture对应的任务完成,并获取结果 46 | System.out.println(twoFuture.get()); 47 | 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 4.0.0 7 | 8 | com.books.dubbo.demo 9 | Demo 10 | 0.0.1-SNAPSHOT 11 | 12 | com.books.dubbo.demo 13 | Provider 14 | 0.0.1-SNAPSHOT 15 | Provider 16 | http://maven.apache.org 17 | 18 | UTF-8 19 | 20 | 21 | 22 | com.books.dubbo.demo 23 | Sdk 24 | 0.0.1-SNAPSHOT 25 | 26 | 27 | junit 28 | junit 29 | 3.8.1 30 | test 31 | 32 | 33 | 34 | 35 | 36 | org.apache.maven.plugins 37 | maven-compiler-plugin 38 | 3.6.0 39 | 40 | 1.8 41 | 1.8 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/src/main/java/org/Chapter5/rxjava/AsyncRpcCall6.java: -------------------------------------------------------------------------------- 1 | package org.Chapter5.rxjava; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.CompletableFuture; 6 | import java.util.stream.Collectors; 7 | 8 | import io.reactivex.Flowable; 9 | import io.reactivex.functions.Consumer; 10 | import io.reactivex.schedulers.Schedulers; 11 | 12 | public class AsyncRpcCall6 { 13 | 14 | public static String rpcCall(String ip, String param) { 15 | 16 | System.out.println(ip + " rpcCall:" + param); 17 | try { 18 | Thread.sleep(2000); 19 | } catch (InterruptedException e) { 20 | // TODO Auto-generated catch block 21 | e.printStackTrace(); 22 | } 23 | 24 | return param; 25 | 26 | } 27 | 28 | public static void main(String[] args) throws InterruptedException { 29 | 30 | // 1.生成ip列表 31 | List ipList = new ArrayList(); 32 | for (int i = 1; i <= 10; ++i) { 33 | ipList.add("192.168.0." + i); 34 | } 35 | 36 | // 2.并发调用 37 | Flowable.fromArray( ipList.toArray(new String[0])) 38 | .flatMap(ip -> //2.1 39 | Flowable.just(ip)//2.2 40 | .subscribeOn(Schedulers.io())//2.3 41 | .map(v -> rpcCall(v, v)))//2.4 42 | .subscribe(new Consumer() { 43 | 44 | @Override 45 | public void accept(String t) throws Exception { 46 | System.out.println(Thread.currentThread().getName() + t); 47 | } 48 | }); 49 | 50 | Thread.sleep(3000); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 4.0.0 7 | 8 | com.jiaduo.async.demo 9 | async-program-demo 10 | 0.0.1-SNAPSHOT 11 | 12 | com.jiaduo.async.demo 13 | ChapterIV 14 | 0.0.1-SNAPSHOT 15 | ChapterIV 16 | http://maven.apache.org 17 | 18 | UTF-8 19 | 20 | 21 | 22 | 23 | org.springframework 24 | spring-context 25 | 5.1.9.RELEASE 26 | 27 | 28 | 29 | org.springframework 30 | spring-core 31 | 5.1.9.RELEASE 32 | 33 | 34 | junit 35 | junit 36 | 3.8.1 37 | test 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/src/main/java/com/books/dubbo/demo/provider/GrettingServiceAsyncImpl.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.provider; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ForkJoinPool; 5 | import java.util.concurrent.SynchronousQueue; 6 | import java.util.concurrent.ThreadPoolExecutor; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | import org.apache.dubbo.common.utils.NamedThreadFactory; 10 | import org.apache.dubbo.rpc.RpcContext; 11 | 12 | import com.books.dubbo.demo.api.GrettingServiceAsync; 13 | 14 | public class GrettingServiceAsyncImpl implements GrettingServiceAsync { 15 | 16 | // 1.创建业务自定义线程池 17 | private final ThreadPoolExecutor bizThreadpool = new ThreadPoolExecutor(8, 16, 1, TimeUnit.MINUTES, 18 | new SynchronousQueue(), new NamedThreadFactory("biz-thread-pool"), 19 | new ThreadPoolExecutor.CallerRunsPolicy()); 20 | 21 | // 2.创建服务处理接口,返回值为CompletableFuture 22 | @Override 23 | public CompletableFuture sayHello(String name) { 24 | 25 | // 2.1 为supplyAsync提供自定义线程池bizThreadpool,避免使用JDK公用线程池(ForkJoinPool.commonPool()) 26 | // 使用CompletableFuture.supplyAsync让服务处理异步化进行处理 27 | // 保存当前线程的上下文 28 | RpcContext context = RpcContext.getContext(); 29 | 30 | return CompletableFuture.supplyAsync(() -> { 31 | try { 32 | Thread.sleep(2000); 33 | } catch (InterruptedException e) { 34 | e.printStackTrace(); 35 | } 36 | System.out.println("async return "); 37 | return "Hello " + name + " " + context.getAttachment("company"); 38 | }, bizThreadpool); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/src/main/java/org/Chapter5/rxjava/AsyncRpcCall5.java: -------------------------------------------------------------------------------- 1 | package org.Chapter5.rxjava; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.CompletableFuture; 6 | import java.util.stream.Collectors; 7 | 8 | import io.reactivex.Flowable; 9 | import io.reactivex.functions.Consumer; 10 | import io.reactivex.schedulers.Schedulers; 11 | 12 | // 13 | 14 | public class AsyncRpcCall5 { 15 | 16 | public static String rpcCall(String ip, String param) { 17 | 18 | System.out.println(Thread.currentThread().getName() + " " + ip + " rpcCall:" + param); 19 | try { 20 | Thread.sleep(2000); 21 | } catch (InterruptedException e) { 22 | // TODO Auto-generated catch block 23 | e.printStackTrace(); 24 | } 25 | 26 | return param; 27 | 28 | } 29 | 30 | public static void main(String[] args) throws InterruptedException { 31 | 32 | //1. 33 | long start = System.currentTimeMillis(); 34 | Flowable.fromCallable(() -> {//1.1 35 | Thread.sleep(1000); // 1.2模拟耗时的操作 36 | return "Done" +Thread.currentThread().getName(); 37 | }) 38 | .subscribeOn(Schedulers.io())//1.3 39 | .observeOn(Schedulers.single())//1.4 40 | .subscribe(new Consumer() { 41 | 42 | @Override 43 | public void accept(String t) throws Exception { 44 | System.out.println(Thread.currentThread().getName() + t); 45 | 46 | } 47 | }, Throwable::printStackTrace);//1.5 48 | 49 | //2. 50 | System.out.println("cost:" + (System.currentTimeMillis() - start)); 51 | 52 | //3. 53 | Thread.sleep(2000000); // 等待流结束 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/src/main/java/com/books/dubbo/demo/provider/GrettingServiceAsyncContextImpl.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.provider; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ForkJoinPool; 5 | import java.util.concurrent.SynchronousQueue; 6 | import java.util.concurrent.ThreadPoolExecutor; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | import org.apache.dubbo.common.utils.NamedThreadFactory; 10 | import org.apache.dubbo.rpc.AsyncContext; 11 | import org.apache.dubbo.rpc.RpcContext; 12 | 13 | import com.books.dubbo.demo.api.GrettingServiceAsync; 14 | import com.books.dubbo.demo.api.GrettingServiceRpcContext; 15 | 16 | public class GrettingServiceAsyncContextImpl implements GrettingServiceRpcContext { 17 | 18 | // 1.创建业务自定义线程池 19 | private final ThreadPoolExecutor bizThreadpool = new ThreadPoolExecutor(8, 16, 1, TimeUnit.MINUTES, 20 | new SynchronousQueue(), new NamedThreadFactory("biz-thread-pool"), 21 | new ThreadPoolExecutor.CallerRunsPolicy()); 22 | 23 | // 2.创建服务处理接口,返回值为CompletableFuture 24 | @Override 25 | public String sayHello(String name) { 26 | 27 | // 2.1开启异步 28 | final AsyncContext asyncContext = RpcContext.startAsync(); 29 | bizThreadpool.execute(() -> { 30 | // 2.2 如果要使用上下文,则必须要放在第一句执行 31 | asyncContext.signalContextSwitch(); 32 | try { 33 | Thread.sleep(500); 34 | } catch (InterruptedException e) { 35 | e.printStackTrace(); 36 | } 37 | // 2.3写回响应 38 | asyncContext.write("Hello " + name + " " + RpcContext.getContext().getAttachment("company")); 39 | }); 40 | 41 | return null; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/src/main/java/org/Chapter5/reactor/StreamTest.java: -------------------------------------------------------------------------------- 1 | package org.Chapter5.reactor; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.stream.Collector; 6 | import java.util.stream.Collectors; 7 | 8 | import io.reactivex.Flowable; 9 | import reactor.core.publisher.Flux; 10 | 11 | public class StreamTest { 12 | 13 | static class Person { 14 | private String name; 15 | private int age; 16 | 17 | public String getName() { 18 | return name; 19 | } 20 | 21 | public void setName(String name) { 22 | this.name = name; 23 | } 24 | 25 | public int getAge() { 26 | return age; 27 | } 28 | 29 | public void setAge(int age) { 30 | this.age = age; 31 | } 32 | 33 | } 34 | 35 | public static List makeList() { 36 | List personList = new ArrayList(); 37 | Person p1 = new Person(); 38 | p1.setAge(10); 39 | p1.setName("zlx"); 40 | personList.add(p1); 41 | 42 | p1 = new Person(); 43 | p1.setAge(12); 44 | p1.setName("jiaduo"); 45 | personList.add(p1); 46 | 47 | p1 = new Person(); 48 | p1.setAge(5); 49 | p1.setName("ruoran"); 50 | personList.add(p1); 51 | return personList; 52 | } 53 | 54 | public static void main(String[] args) { 55 | 56 | // 1.创建person列表 57 | List personList = makeList(); 58 | 59 | // 2.执行过滤与输出 60 | Flux.fromArray(personList.toArray(new Person[0]))// 2.1转换列表为Flowable流对象 61 | .filter(person -> person.getAge() >= 10)// 2.2过滤 62 | .map(person -> person.getName())// 2.3.映射转换 63 | .subscribe(System.out::println);// 2.4订阅输出 64 | 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/FutureTask/AsyncFutureExample.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter.FutureTask; 2 | 3 | import java.util.concurrent.ExecutionException; 4 | import java.util.concurrent.FutureTask; 5 | 6 | public class AsyncFutureExample { 7 | 8 | public static String doSomethingA() { 9 | 10 | try { 11 | Thread.sleep(2000); 12 | } catch (InterruptedException e) { 13 | e.printStackTrace(); 14 | } 15 | System.out.println("--- doSomethingA---"); 16 | 17 | return "TaskAResult"; 18 | } 19 | 20 | public static String doSomethingB() { 21 | try { 22 | Thread.sleep(2000); 23 | } catch (InterruptedException e) { 24 | e.printStackTrace(); 25 | } 26 | System.out.println("--- doSomethingB---"); 27 | return "TaskBResult"; 28 | 29 | } 30 | 31 | public static void main(String[] args) throws InterruptedException, ExecutionException { 32 | 33 | long start = System.currentTimeMillis(); 34 | 35 | // 1.创建future任务 36 | FutureTask futureTask = new FutureTask(() -> { 37 | String result = null; 38 | try { 39 | result = doSomethingA(); 40 | 41 | } catch (Exception e) { 42 | e.printStackTrace(); 43 | } 44 | return result; 45 | }); 46 | 47 | // 2.开启异步单元执行任务A 48 | Thread thread = new Thread(futureTask, "threadA"); 49 | thread.start(); 50 | 51 | // 3.执行任务B 52 | String taskBResult = doSomethingB(); 53 | 54 | // 4.同步等待线程A运行结束 55 | String taskAResult = futureTask.get(); 56 | //5.打印两个任务执行结果 57 | System.out.println(taskAResult + " " + taskBResult); 58 | System.out.println(System.currentTimeMillis() - start); 59 | 60 | } 61 | } -------------------------------------------------------------------------------- /dubbo-demo/Sdk/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 4.0.0 7 | 8 | com.books.dubbo.demo 9 | Demo 10 | 0.0.1-SNAPSHOT 11 | 12 | com.books.dubbo.demo 13 | Sdk 14 | 0.0.1-SNAPSHOT 15 | Sdk 16 | http://maven.apache.org 17 | 18 | UTF-8 19 | 20 | 21 | 22 | junit 23 | junit 24 | 3.8.1 25 | test 26 | 27 | 28 | 29 | org.apache.jmeter 30 | ApacheJMeter_core 31 | 3.0 32 | 33 | 34 | org.apache.jmeter 35 | ApacheJMeter_java 36 | 3.0 37 | 38 | 39 | 40 | 41 | 42 | 43 | org.apache.maven.plugins 44 | maven-compiler-plugin 45 | 3.6.0 46 | 47 | 1.8 48 | 1.8 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/src/main/java/com/books/dubbo/demo/provider/mydispatcher/MyThreadPool.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.provider.mydispatcher; 2 | 3 | import java.util.concurrent.Executor; 4 | import java.util.concurrent.LinkedBlockingQueue; 5 | import java.util.concurrent.SynchronousQueue; 6 | import java.util.concurrent.ThreadPoolExecutor; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | import org.apache.dubbo.common.Constants; 10 | import org.apache.dubbo.common.URL; 11 | import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; 12 | import org.apache.dubbo.common.threadpool.ThreadPool; 13 | import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; 14 | 15 | public class MyThreadPool implements ThreadPool { 16 | 17 | @Override 18 | public Executor getExecutor(URL url) { 19 | String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME); 20 | int cores = url.getParameter(Constants.CORE_THREADS_KEY, Constants.DEFAULT_CORE_THREADS); 21 | int threads = url.getParameter(Constants.THREADS_KEY, Integer.MAX_VALUE); 22 | int queues = url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES); 23 | int alive = url.getParameter(Constants.ALIVE_KEY, Constants.DEFAULT_ALIVE); 24 | return new ThreadPoolExecutor(cores, threads, alive, TimeUnit.MILLISECONDS, 25 | queues == 0 ? new SynchronousQueue() : 26 | (queues < 0 ? new LinkedBlockingQueue() 27 | : new LinkedBlockingQueue(queues)), 28 | new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url)); 29 | } 30 | } -------------------------------------------------------------------------------- /dubbo-demo/Consumer/src/main/java/org/apache/dubbo/demo/consumer/APiConsumerForProviderAsync.java: -------------------------------------------------------------------------------- 1 | package org.apache.dubbo.demo.consumer; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | 5 | import org.apache.dubbo.config.ApplicationConfig; 6 | import org.apache.dubbo.config.ReferenceConfig; 7 | import org.apache.dubbo.config.RegistryConfig; 8 | import org.apache.dubbo.rpc.RpcContext; 9 | 10 | import com.books.dubbo.demo.api.GreetingService; 11 | import com.books.dubbo.demo.api.GrettingServiceAsync; 12 | 13 | public class APiConsumerForProviderAsync { 14 | public static void main(String[] args) throws InterruptedException { 15 | //1.创建服务引用实例,并设置 16 | ReferenceConfig referenceConfig = new ReferenceConfig(); 17 | referenceConfig.setApplication(new ApplicationConfig("first-dubbo-consumer")); 18 | referenceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); 19 | referenceConfig.setInterface(GrettingServiceAsync.class); 20 | referenceConfig.setTimeout(5000); 21 | //referenceConfig.setCluster("myCluster"); 22 | 23 | referenceConfig.setVersion("1.0.0"); 24 | referenceConfig.setGroup("dubbo"); 25 | 26 | //2.服务引用 27 | GrettingServiceAsync greetingService = referenceConfig.get(); 28 | 29 | //3.设置隐士参数 30 | RpcContext.getContext().setAttachment("company", "alibaba"); 31 | //RpcContext.getContext().set("ip", "30.39.148.197"); 32 | 33 | //4.获取future并设置回调 34 | CompletableFuture future = greetingService.sayHello("world"); 35 | future.whenComplete((v, t) -> { 36 | if (t != null) { 37 | t.printStackTrace(); 38 | } else { 39 | System.out.println(v); 40 | } 41 | 42 | }); 43 | 44 | Thread.currentThread().join(); 45 | 46 | } 47 | } -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/src/main/java/org/ChapterIV/Async/AsyncAnnotationExample.java: -------------------------------------------------------------------------------- 1 | package org.ChapterIV.Async; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.Future; 5 | 6 | import org.springframework.context.annotation.ComponentScan; 7 | import org.springframework.scheduling.annotation.Async; 8 | import org.springframework.scheduling.annotation.EnableAsync; 9 | import org.springframework.scheduling.annotation.Scheduled; 10 | import org.springframework.stereotype.Component; 11 | 12 | @EnableAsync // 开启异步执行 13 | @Component // 注入该Bean到Spring容器 14 | public class AsyncAnnotationExample { 15 | 16 | // @Scheduled(cron = "*/5 * * * * ?") // 每隔5秒执行一次 17 | public void asyncPrint1() { 18 | try { 19 | System.out.println(Thread.currentThread().getName()); 20 | } catch (Exception e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | 25 | @Async 26 | public void printMessages() { 27 | for (int i = 0; i < 6; i++) { 28 | try { 29 | Thread.sleep(5000); 30 | System.out.println(Thread.currentThread().getName() + " Message" + i); 31 | } catch (Exception e) { 32 | e.printStackTrace(); 33 | } 34 | } 35 | } 36 | 37 | @Async 38 | public void testException() throws Exception { 39 | if (true) 40 | throw new Exception("error"); 41 | } 42 | 43 | @Async 44 | public CompletableFuture doSomething() { 45 | 46 | // 1.创建future 47 | CompletableFuture result = new CompletableFuture(); 48 | // 2.模拟任务执行 49 | try { 50 | Thread.sleep(1000); 51 | System.out.println(Thread.currentThread().getName() + "doSomething"); 52 | } catch (Exception e) { 53 | e.printStackTrace(); 54 | } 55 | result.complete("done"); 56 | 57 | // 3.返回结果 58 | return result; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/src/main/java/com/books/dubbo/demo/provider/ApiProviderForExecuteLimit.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.provider; 2 | 3 | import java.io.IOException; 4 | import java.util.ArrayList; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | 8 | import org.apache.dubbo.config.ApplicationConfig; 9 | import org.apache.dubbo.config.MethodConfig; 10 | import org.apache.dubbo.config.RegistryConfig; 11 | import org.apache.dubbo.config.ServiceConfig; 12 | 13 | import com.books.dubbo.demo.api.GreetingService; 14 | 15 | public class ApiProviderForExecuteLimit { 16 | 17 | public static void main(String[] args) throws IOException { 18 | 19 | ServiceConfig serviceConfig = new ServiceConfig(); 20 | serviceConfig.setApplication(new ApplicationConfig("first-dubbo-provider")); 21 | serviceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); 22 | serviceConfig.setInterface(GreetingService.class); 23 | serviceConfig.setRef(new GreetingServiceImpl()); 24 | 25 | serviceConfig.setVersion("1.0.0"); 26 | serviceConfig.setGroup("dubbo"); 27 | 28 | //设置并发控制数 29 | serviceConfig.setExecutes(10); 30 | 31 | final List methodList = new ArrayList(); 32 | 33 | MethodConfig methodConfig = new MethodConfig(); 34 | methodConfig.setExecutes(10); 35 | methodConfig.setName("sayHello"); 36 | methodList.add(methodConfig); 37 | serviceConfig.setMethods(methodList); 38 | 39 | // 设置线程池策略 40 | HashMap parameters = new HashMap<>(); 41 | parameters.put("threadpool", "mythreadpool"); 42 | serviceConfig.setParameters(parameters); 43 | 44 | serviceConfig.export(); 45 | 46 | System.out.println("server is started"); 47 | System.in.read(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 4.0.0 7 | 8 | com.jiaduo.async.demo 9 | async-program-demo 10 | 0.0.1-SNAPSHOT 11 | 12 | com.jiaduo.async.demo 13 | Chapter5 14 | 0.0.1-SNAPSHOT 15 | Chapter5 16 | http://maven.apache.org 17 | 18 | UTF-8 19 | 20 | 21 | 22 | 23 | io.projectreactor 24 | reactor-bom 25 | Dysprosium-M1 26 | pom 27 | import 28 | 29 | 30 | 31 | 32 | 33 | 34 | io.projectreactor 35 | reactor-core 36 | 37 | 38 | io.projectreactor 39 | reactor-test 40 | test 41 | 42 | 43 | 44 | io.reactivex.rxjava2 45 | rxjava 46 | 2.2.10 47 | 48 | 49 | junit 50 | junit 51 | 3.8.1 52 | test 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /dubbo-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | 6 | com.books.dubbo.demo 7 | Demo 8 | 0.0.1-SNAPSHOT 9 | pom 10 | 11 | Demo 12 | http://maven.apache.org 13 | 14 | 15 | UTF-8 16 | 2.7.1 17 | 2.7.0 18 | 19 | 20 | 21 | 22 | org.apache.dubbo 23 | dubbo 24 | ${dubbo.version} 25 | 26 | 27 | 28 | 29 | org.apache.dubbo 30 | dubbo-dependencies-zookeeper 31 | 2.7.1 32 | pom 33 | 34 | 35 | junit 36 | junit 37 | 3.8.1 38 | test 39 | 40 | 41 | 42 | org.apache.zookeeper 43 | zookeeper 44 | 3.4.5 45 | pom 46 | 47 | 48 | 49 | 50 | Provider 51 | Consumer 52 | Sdk 53 | 54 | 55 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/src/main/java/org/Chapter5/rxjava/StreamTest.java: -------------------------------------------------------------------------------- 1 | package org.Chapter5.rxjava; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | 7 | import io.reactivex.Flowable; 8 | 9 | public class StreamTest { 10 | static class Person { 11 | private String name; 12 | private int age; 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | 22 | public int getAge() { 23 | return age; 24 | } 25 | 26 | public void setAge(int age) { 27 | this.age = age; 28 | } 29 | 30 | } 31 | 32 | public static List makeList() { 33 | List personList = new ArrayList(); 34 | Person p1 = new Person(); 35 | p1.setAge(10); 36 | p1.setName("zlx"); 37 | personList.add(p1); 38 | 39 | p1 = new Person(); 40 | p1.setAge(12); 41 | p1.setName("jiaduo"); 42 | personList.add(p1); 43 | 44 | p1 = new Person(); 45 | p1.setAge(5); 46 | p1.setName("ruoran"); 47 | personList.add(p1); 48 | return personList; 49 | } 50 | 51 | public static void main(String[] args) { 52 | 53 | // 1.创建person列表 54 | List personList = makeList(); 55 | 56 | // 2.执行过滤与输出 57 | Flowable.fromArray(personList.toArray(new Person[0]))// 2.1转换列表为Flowable流对象 58 | .filter(person -> person.getAge() >= 10)// 2.2过滤 59 | .map(person -> person.getName())// 2.3.映射转换 60 | .subscribe(System.out::println);// 2.4订阅输出 61 | 62 | Flowable source = Flowable.fromArray(personList.toArray(new Person[0])); 63 | Flowable filterSource = source.filter(person -> person.getAge() >= 10); 64 | Flowable nameSource = filterSource.map(person -> person.getName()); 65 | nameSource.subscribe(System.out::println); 66 | 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /async-program-demo/Chapter5/src/main/java/org/Chapter5/rxjava/AsyncRpcCall2.java: -------------------------------------------------------------------------------- 1 | package org.Chapter5.rxjava; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.CompletableFuture; 6 | import java.util.concurrent.LinkedBlockingQueue; 7 | import java.util.concurrent.ThreadPoolExecutor; 8 | import java.util.concurrent.TimeUnit; 9 | import java.util.stream.Collectors; 10 | 11 | import io.reactivex.Flowable; 12 | import io.reactivex.functions.Consumer; 13 | import io.reactivex.schedulers.Schedulers; 14 | 15 | public class AsyncRpcCall2 { 16 | 17 | public static String rpcCall(String ip, String param) { 18 | 19 | System.out.println(ip + " rpcCall:" + param); 20 | try { 21 | Thread.sleep(2000); 22 | } catch (InterruptedException e) { 23 | // TODO Auto-generated catch block 24 | e.printStackTrace(); 25 | } 26 | 27 | return param; 28 | 29 | } 30 | 31 | // 0自定义线程池 32 | private final static ThreadPoolExecutor POOL_EXECUTOR = new ThreadPoolExecutor(10, 10, 1, TimeUnit.MINUTES, 33 | new LinkedBlockingQueue<>(5), new ThreadPoolExecutor.CallerRunsPolicy()); 34 | 35 | public static void main(String[] args) { 36 | 37 | // 1.生成ip列表 38 | List ipList = new ArrayList(); 39 | for (int i = 1; i <= 10; ++i) { 40 | ipList.add("192.168.0." + i); 41 | } 42 | 43 | // 2.并发调用 44 | long start = System.currentTimeMillis(); 45 | 46 | Flowable.fromArray(ipList.toArray(new String[0])) 47 | .flatMap(ip -> // 2.1 48 | Flowable.just(ip)// 2.2 49 | .subscribeOn(Schedulers.from(POOL_EXECUTOR))// 2.3 50 | .map(v -> rpcCall(v, v)))// 2.4 51 | .blockingSubscribe(System.out::println);// 2.5 52 | 53 | // 3.打印耗时 54 | System.out.println("cost:" + (System.currentTimeMillis() - start)); 55 | 56 | //4.关闭线程池 57 | POOL_EXECUTOR.shutdown(); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/metaq/ProducerAsync.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.metaq; 2 | 3 | import org.apache.rocketmq.client.exception.MQClientException; 4 | import org.apache.rocketmq.client.producer.DefaultMQProducer; 5 | import org.apache.rocketmq.client.producer.SendCallback; 6 | import org.apache.rocketmq.client.producer.SendResult; 7 | import org.apache.rocketmq.common.message.Message; 8 | import org.apache.rocketmq.remoting.common.RemotingHelper; 9 | 10 | public class ProducerAsync { 11 | public static void main(String[] args) throws MQClientException, InterruptedException { 12 | 13 | // 1. 创建生产者实例 14 | DefaultMQProducer producer = new DefaultMQProducer("jiaduo-producer-group"); 15 | // 2. 设置nameserver地址,多个可以使用;分隔 16 | producer.setNamesrvAddr("127.0.0.1:9876"); 17 | producer.setSendMsgTimeout(1000); 18 | producer.setRetryTimesWhenSendAsyncFailed(0); 19 | // 3. 启动生产者 20 | producer.start(); 21 | 22 | // 4. 发送消息 23 | for (int i = 0; i < 20; i++) { 24 | try { 25 | 26 | // 4.1 创建消息体,topic为TopicTest,tag为TagA 27 | Message msg = new Message("TopicTest" /* Topic */, "TagA" /* Tag */, i + "", 28 | ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */ 29 | ); 30 | 31 | // 4.2 异步发送消息 32 | producer.send(msg, new SendCallback() { 33 | 34 | @Override 35 | public void onSuccess(SendResult sendResult) { 36 | System.out.printf("onSuccess:%s%n", sendResult); 37 | 38 | } 39 | 40 | @Override 41 | public void onException(Throwable e) { 42 | System.out.printf("onException:%s%n", e); 43 | 44 | } 45 | }); 46 | // 4.3 47 | Thread.sleep(500); 48 | } catch (Exception e) { 49 | e.printStackTrace(); 50 | } 51 | } 52 | 53 | // 5. 关闭 54 | Thread.sleep(100000); 55 | producer.shutdown(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /async-program-demo/Second-Chapter/src/main/java/org/Second/Chapter/ThreadPool/AsyncThreadPoolExample1.java: -------------------------------------------------------------------------------- 1 | package org.Second.Chapter.ThreadPool; 2 | 3 | import java.util.concurrent.ArrayBlockingQueue; 4 | import java.util.concurrent.ExecutionException; 5 | import java.util.concurrent.Future; 6 | import java.util.concurrent.LinkedBlockingQueue; 7 | import java.util.concurrent.ThreadPoolExecutor; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | /** 11 | * Hello world! 12 | * 13 | */ 14 | public class AsyncThreadPoolExample1 { 15 | 16 | public static void doSomethingA() { 17 | 18 | try { 19 | Thread.sleep(2000); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | System.out.println("--- doSomethingA---"); 24 | } 25 | 26 | public static void doSomethingB() { 27 | try { 28 | Thread.sleep(2000); 29 | } catch (InterruptedException e) { 30 | e.printStackTrace(); 31 | } 32 | System.out.println("--- doSomethingB---"); 33 | 34 | } 35 | 36 | // 0自定义线程池 37 | private final static int AVALIABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); 38 | private final static ThreadPoolExecutor POOL_EXECUTOR = new ThreadPoolExecutor(AVALIABLE_PROCESSORS, 39 | AVALIABLE_PROCESSORS * 2, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(5), 40 | new ThreadPoolExecutor.CallerRunsPolicy()); 41 | 42 | public static void main(String[] args) throws InterruptedException, ExecutionException { 43 | 44 | long start = System.currentTimeMillis(); 45 | 46 | // 1.开启异步单元执行任务A 47 | POOL_EXECUTOR.execute(() -> { 48 | try { 49 | doSomethingA(); 50 | 51 | } catch (Exception e) { 52 | e.printStackTrace(); 53 | } 54 | }); 55 | 56 | // 2.执行任务B 57 | doSomethingB(); 58 | 59 | // 3.同步等待线程A运行结束 60 | System.out.println(System.currentTimeMillis() - start); 61 | 62 | // 4.挂起当前线程 63 | Thread.currentThread().join(); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 4.0.0 7 | 8 | com.jiaduo.async.demo 9 | async-program-demo 10 | 0.0.1-SNAPSHOT 11 | 12 | com.jiaduo.async.demo 13 | Chapter8 14 | 0.0.1-SNAPSHOT 15 | Chapter8 16 | http://maven.apache.org 17 | 18 | UTF-8 19 | 20 | 21 | 22 | org.apache.rocketmq 23 | rocketmq-client 24 | 4.5.2 25 | 26 | 27 | junit 28 | junit 29 | 3.8.1 30 | test 31 | 32 | 33 | 34 | io.netty 35 | netty-all 36 | 4.1.1.Final 37 | 38 | 39 | 40 | 41 | com.lmax 42 | disruptor 43 | 3.4.2 44 | 45 | 46 | 47 | io.reactivex.rxjava2 48 | rxjava 49 | 2.2.10 50 | 51 | 52 | 53 | com.typesafe.akka 54 | akka-remote_2.11 55 | 2.3.7 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/CompletableFuture/TestCompletableFutureWhenComplete.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter.CompletableFuture; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ExecutionException; 5 | import java.util.concurrent.LinkedBlockingQueue; 6 | import java.util.concurrent.ThreadPoolExecutor; 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.concurrent.TimeoutException; 9 | import java.util.function.BiConsumer; 10 | import java.util.function.Supplier; 11 | 12 | public class TestCompletableFutureWhenComplete { 13 | public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException { 14 | 15 | // 1.创建一个CompletableFuture对象 16 | CompletableFuture future = CompletableFuture.supplyAsync(new Supplier() { 17 | 18 | @Override 19 | public String get() { 20 | // 1.1模拟异步任务执行 21 | try { 22 | Thread.sleep(1000); 23 | } catch (InterruptedException e) { 24 | e.printStackTrace(); 25 | } 26 | // 1.2返回计算结果 27 | return "hello,jiaduo"; 28 | } 29 | }); 30 | 31 | // 2.添加回调函数 32 | future.whenComplete(new BiConsumer() { 33 | 34 | @Override 35 | public void accept(String t, Throwable u) { 36 | // 2.1如果没有异常,打印异步任务结果 37 | if (null == u) { 38 | System.out.println("1"); 39 | } else { 40 | // 2.2打印异常信息 41 | System.out.println(u.getLocalizedMessage()); 42 | } 43 | } 44 | }); 45 | 46 | // 2.添加回调函数 47 | future.whenComplete(new BiConsumer() { 48 | 49 | @Override 50 | public void accept(String t, Throwable u) { 51 | // 2.1如果没有异常,打印异步任务结果 52 | if (null == u) { 53 | System.out.println("2"); 54 | } else { 55 | // 2.2打印异常信息 56 | System.out.println(u.getLocalizedMessage()); 57 | 58 | } 59 | } 60 | }); 61 | 62 | // 3.挂起当前线程,等待异步任务执行完毕 63 | Thread.currentThread().join(); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /async-program-demo/Second-Chapter/src/main/java/org/Second/Chapter/ThreadPool/AsyncThreadPoolExample2.java: -------------------------------------------------------------------------------- 1 | package org.Second.Chapter.ThreadPool; 2 | 3 | import java.util.concurrent.ArrayBlockingQueue; 4 | import java.util.concurrent.ExecutionException; 5 | import java.util.concurrent.Future; 6 | import java.util.concurrent.LinkedBlockingQueue; 7 | import java.util.concurrent.ThreadPoolExecutor; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | /** 11 | * Hello world! 12 | * 13 | */ 14 | public class AsyncThreadPoolExample2 { 15 | 16 | public static void doSomethingA() { 17 | 18 | try { 19 | Thread.sleep(2000); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | System.out.println("--- doSomethingA---"); 24 | } 25 | 26 | public static void doSomethingB() { 27 | try { 28 | Thread.sleep(2000); 29 | } catch (InterruptedException e) { 30 | e.printStackTrace(); 31 | } 32 | System.out.println("--- doSomethingB---"); 33 | 34 | } 35 | 36 | // 0自定义线程池 37 | private final static int AVALIABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); 38 | private final static ThreadPoolExecutor POOL_EXECUTOR = new ThreadPoolExecutor(AVALIABLE_PROCESSORS, 39 | AVALIABLE_PROCESSORS * 2, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(5), 40 | new ThreadPoolExecutor.CallerRunsPolicy()); 41 | 42 | public static void main(String[] args) throws InterruptedException, ExecutionException { 43 | 44 | long start = System.currentTimeMillis(); 45 | 46 | // 1.开启异步单元执行任务A 47 | POOL_EXECUTOR.execute(() -> { 48 | try { 49 | doSomethingA(); 50 | 51 | } catch (Exception e) { 52 | e.printStackTrace(); 53 | } 54 | }); 55 | 56 | // 2.执行任务B 57 | POOL_EXECUTOR.execute(() -> { 58 | try { 59 | doSomethingB(); 60 | 61 | } catch (Exception e) { 62 | e.printStackTrace(); 63 | } 64 | }); 65 | 66 | // 3.同步等待线程A运行结束 67 | System.out.println(System.currentTimeMillis() - start); 68 | 69 | // 4.挂起当前线程 70 | Thread.currentThread().join(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/CompletableFuture/StreamTest.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter.CompletableFuture; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.stream.Collector; 6 | import java.util.stream.Collectors; 7 | 8 | public class StreamTest { 9 | 10 | static class Person { 11 | private String name; 12 | private int age; 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | 22 | public int getAge() { 23 | return age; 24 | } 25 | 26 | public void setAge(int age) { 27 | this.age = age; 28 | } 29 | 30 | } 31 | 32 | public static List makeList() { 33 | List personList = new ArrayList(); 34 | Person p1 = new Person(); 35 | p1.setAge(10); 36 | p1.setName("zlx"); 37 | personList.add(p1); 38 | 39 | p1 = new Person(); 40 | p1.setAge(12); 41 | p1.setName("jiaduo"); 42 | personList.add(p1); 43 | 44 | p1 = new Person(); 45 | p1.setAge(5); 46 | p1.setName("ruoran"); 47 | personList.add(p1); 48 | return personList; 49 | } 50 | 51 | public static void useStream(List personList) { 52 | 53 | List nameList = personList.stream().filter(person -> person.getAge() >= 10)// 1.过滤大于等于10的 54 | .map(person -> person.getName())// 2.使用map映射元素 55 | .collect(Collectors.toList());// 3.收集映射后元素 56 | 57 | nameList.stream().forEach(name -> System.out.println(name)); 58 | } 59 | 60 | public static void noStream(List personList) { 61 | 62 | List nameList = new ArrayList<>(); 63 | 64 | for (Person person : personList) { 65 | if (person.age >= 10) { 66 | nameList.add(person.getName()); 67 | } 68 | } 69 | 70 | for (String name : nameList) { 71 | System.out.println(name); 72 | } 73 | 74 | } 75 | 76 | public static void main(String[] args) { 77 | 78 | List personList = makeList(); 79 | 80 | noStream(personList); 81 | 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/CompletableFuture/TestTwoCompletableFuture.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter.CompletableFuture; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ExecutionException; 5 | import java.util.function.Supplier; 6 | 7 | public class TestTwoCompletableFuture { 8 | 9 | // 1.异步任务,返回future 10 | public static CompletableFuture doSomethingOne(String encodedCompanyId) { 11 | // 1.1创建异步任务 12 | return CompletableFuture.supplyAsync(new Supplier() { 13 | 14 | @Override 15 | public String get() { 16 | 17 | // 1.1.1休眠1s,模拟任务计算 18 | try { 19 | Thread.sleep(1000); 20 | } catch (InterruptedException e) { 21 | // TODO Auto-generated catch block 22 | e.printStackTrace(); 23 | } 24 | 25 | // 1.1.2 解密,并返回结果 26 | String id = encodedCompanyId; 27 | return id; 28 | } 29 | }); 30 | } 31 | 32 | // 2.开启异步任务,返回future 33 | public static CompletableFuture doSomethingTwo(String companyId) { 34 | return CompletableFuture.supplyAsync(new Supplier() { 35 | 36 | @Override 37 | public String get() { 38 | 39 | // 2.1,休眠3s,模拟计算 40 | try { 41 | Thread.sleep(3000); 42 | } catch (InterruptedException e) { 43 | // TODO Auto-generated catch block 44 | e.printStackTrace(); 45 | } 46 | 47 | // 2.2 查询公司信息,转换为str,并返回 48 | String str = companyId + ":alibaba"; 49 | return str; 50 | } 51 | }); 52 | } 53 | 54 | public static void main(String[] args) throws InterruptedException, ExecutionException { 55 | 56 | // I,等doSomethingOne执行完毕后,接着执行doSomethingTwo 57 | CompletableFuture result = doSomethingOne("123").thenCompose(id -> doSomethingTwo(id)); 58 | System.out.println(result.get()); 59 | 60 | // II,等doSomethingOne和doSomethingTwo都完成后,使用它们的结果做一件事 61 | result = doSomethingOne("123").thenCombine(doSomethingTwo("456"), (one, two) -> { 62 | return one + " " + two; 63 | }); 64 | System.out.println(result.get()); 65 | 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/metaq/Consumer.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.metaq; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | import java.util.List; 5 | 6 | import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer; 7 | import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext; 8 | import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; 9 | import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; 10 | import org.apache.rocketmq.client.exception.MQClientException; 11 | import org.apache.rocketmq.common.consumer.ConsumeFromWhere; 12 | import org.apache.rocketmq.common.message.MessageExt; 13 | import org.apache.rocketmq.remoting.common.RemotingHelper; 14 | 15 | public class Consumer { 16 | 17 | public static void main(String[] args) throws InterruptedException, MQClientException { 18 | 19 | // 1. 创建消费实例 和 配置ns地址 20 | DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("my-consumer-group"); 21 | consumer.setNamesrvAddr("127.0.0.1:9876"); 22 | 23 | // 2. 消费属性配置 24 | consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); 25 | 26 | // 3. 订阅TopicTest topic下所有tag 27 | consumer.subscribe("TopicTest", "*"); 28 | // 4. 注册回调 29 | consumer.registerMessageListener(new MessageListenerConcurrently() { 30 | 31 | @Override 32 | public ConsumeConcurrentlyStatus consumeMessage(List msgs, ConsumeConcurrentlyContext context) { 33 | for (MessageExt msg : msgs) { 34 | String body = ""; 35 | try { 36 | body = new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET); 37 | } catch (UnsupportedEncodingException e) { 38 | e.printStackTrace(); 39 | } 40 | System.out.printf("%s Receive New Messages: %s %s %n", Thread.currentThread().getName(), 41 | msg.getMsgId(), body); 42 | 43 | } 44 | return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; 45 | } 46 | }); 47 | 48 | // 5.启动消费实例 49 | consumer.start(); 50 | 51 | System.out.printf("Consumer Started.%n"); 52 | } 53 | } -------------------------------------------------------------------------------- /async-program-demo/ChapterIV/src/main/resources/beans.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 15 | 16 | 18 | 19 | 21 | 22 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 37 | 38 | 40 | 41 | 42 | 44 | 45 | 46 | 48 | 49 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/FutureTask/AsyncFutureExample3.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter.FutureTask; 2 | 3 | import java.util.concurrent.Callable; 4 | import java.util.concurrent.ExecutionException; 5 | import java.util.concurrent.Future; 6 | import java.util.concurrent.FutureTask; 7 | import java.util.concurrent.LinkedBlockingQueue; 8 | import java.util.concurrent.ThreadPoolExecutor; 9 | import java.util.concurrent.TimeUnit; 10 | 11 | /** 12 | * Hello world! 13 | * 14 | */ 15 | public class AsyncFutureExample3 { 16 | 17 | public static String doSomethingA() { 18 | 19 | try { 20 | Thread.sleep(2000); 21 | } catch (InterruptedException e) { 22 | e.printStackTrace(); 23 | } 24 | System.out.println("--- doSomethingA---"); 25 | 26 | return "TaskAResult"; 27 | } 28 | 29 | public static String doSomethingB() { 30 | try { 31 | Thread.sleep(2000); 32 | } catch (InterruptedException e) { 33 | e.printStackTrace(); 34 | } 35 | System.out.println("--- doSomethingB---"); 36 | return "TaskBResult"; 37 | 38 | } 39 | 40 | // 0自定义线程池 41 | private final static int AVALIABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); 42 | private final static ThreadPoolExecutor POOL_EXECUTOR = new ThreadPoolExecutor(AVALIABLE_PROCESSORS, 43 | AVALIABLE_PROCESSORS * 2, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(5), 44 | new ThreadPoolExecutor.CallerRunsPolicy()); 45 | 46 | public static void main(String[] args) throws InterruptedException, ExecutionException { 47 | 48 | long start = System.currentTimeMillis(); 49 | 50 | // 1.开启异步单元执行任务A 51 | Future futureTask = POOL_EXECUTOR.submit(() -> { 52 | String result = null; 53 | try { 54 | result = doSomethingA(); 55 | 56 | } catch (Exception e) { 57 | e.printStackTrace(); 58 | } 59 | return result; 60 | }); 61 | 62 | // 2.执行任务B 63 | String taskBResult = doSomethingB(); 64 | 65 | // 3.同步等待线程A运行结束 66 | String taskAResult = futureTask.get(); 67 | // 4.打印两个任务执行结果 68 | System.out.println(taskAResult + " " + taskBResult); 69 | System.out.println(System.currentTimeMillis() - start); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/CompletableFuture/TestCompletableFutureSet.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter.CompletableFuture; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ExecutionException; 5 | import java.util.concurrent.LinkedBlockingQueue; 6 | import java.util.concurrent.ThreadPoolExecutor; 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.concurrent.TimeoutException; 9 | import java.util.function.BiConsumer; 10 | 11 | public class TestCompletableFutureSet { 12 | // 0自定义线程池 13 | private final static int AVALIABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); 14 | private final static ThreadPoolExecutor POOL_EXECUTOR = new ThreadPoolExecutor(AVALIABLE_PROCESSORS, 15 | AVALIABLE_PROCESSORS * 2, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(5), 16 | new ThreadPoolExecutor.CallerRunsPolicy()); 17 | 18 | public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException { 19 | 20 | // 1.创建一个CompletableFuture对象 21 | CompletableFuture future = new CompletableFuture(); 22 | 23 | // 2.开启线程计算任务结果,并设置 24 | POOL_EXECUTOR.execute(() -> { 25 | 26 | // 2.1休眠3s,模拟任务计算 27 | try { 28 | Thread.sleep(3000); 29 | } catch (InterruptedException e) { 30 | // TODO Auto-generated catch block 31 | e.printStackTrace(); 32 | } 33 | // 2.2设置计算结果到future 34 | System.out.println("----" + Thread.currentThread().getName() + " set future result----"); 35 | future.complete("hello,jiaduo"); 36 | 37 | }); 38 | 39 | // 3.等待计算结果 40 | System.out.println("---main thread wait future result---"); 41 | System.out.println(future.get()); 42 | // System.out.println(future.get(1000,TimeUnit.MILLISECONDS)); 43 | System.out.println("---main thread got future result---"); 44 | 45 | future.whenComplete(new BiConsumer() { 46 | 47 | @Override 48 | public void accept(String t, Throwable u) { 49 | 50 | if (null == u) { 51 | System.out.println(t); 52 | } else { 53 | System.out.println(u.getLocalizedMessage()); 54 | 55 | } 56 | } 57 | }); 58 | } 59 | } -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/FutureTask/AsyncFutureExample2.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter.FutureTask; 2 | 3 | import java.util.concurrent.Callable; 4 | import java.util.concurrent.ExecutionException; 5 | import java.util.concurrent.FutureTask; 6 | import java.util.concurrent.LinkedBlockingQueue; 7 | import java.util.concurrent.ThreadPoolExecutor; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | /** 11 | * Hello world! 12 | * 13 | */ 14 | public class AsyncFutureExample2 { 15 | 16 | public static String doSomethingA() { 17 | 18 | try { 19 | Thread.sleep(2000); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | System.out.println("--- doSomethingA---"); 24 | 25 | return "TaskAResult"; 26 | } 27 | 28 | public static String doSomethingB() { 29 | try { 30 | Thread.sleep(2000); 31 | } catch (InterruptedException e) { 32 | e.printStackTrace(); 33 | } 34 | System.out.println("--- doSomethingB---"); 35 | return "TaskBResult"; 36 | 37 | } 38 | 39 | // 0自定义线程池 40 | private final static int AVALIABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); 41 | private final static ThreadPoolExecutor POOL_EXECUTOR = new ThreadPoolExecutor(AVALIABLE_PROCESSORS, 42 | AVALIABLE_PROCESSORS * 2, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(5), 43 | new ThreadPoolExecutor.CallerRunsPolicy()); 44 | 45 | public static void main(String[] args) throws InterruptedException, ExecutionException { 46 | 47 | long start = System.currentTimeMillis(); 48 | 49 | // 1.创建future任务 50 | FutureTask futureTask = new FutureTask(() -> { 51 | String result = null; 52 | try { 53 | result = doSomethingA(); 54 | 55 | } catch (Exception e) { 56 | e.printStackTrace(); 57 | } 58 | return result; 59 | }); 60 | 61 | // 2.开启异步单元执行任务A 62 | POOL_EXECUTOR.execute(futureTask); 63 | 64 | // 3.执行任务B 65 | String taskBResult = doSomethingB(); 66 | 67 | // 4.同步等待线程A运行结束 68 | String taskAResult = futureTask.get(); 69 | // 5.打印两个任务执行结果 70 | System.out.println(taskAResult + " " + taskBResult); 71 | System.out.println(System.currentTimeMillis() - start); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /dubbo-demo/Consumer/src/main/java/org/apache/dubbo/demo/consumer/APiAsyncConsumerForCompletableFuture2.java: -------------------------------------------------------------------------------- 1 | package org.apache.dubbo.demo.consumer; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ExecutionException; 5 | 6 | import org.apache.dubbo.config.ApplicationConfig; 7 | import org.apache.dubbo.config.ReferenceConfig; 8 | import org.apache.dubbo.config.RegistryConfig; 9 | import org.apache.dubbo.rpc.RpcContext; 10 | 11 | import com.books.dubbo.demo.api.GreetingService; 12 | 13 | public class APiAsyncConsumerForCompletableFuture2 { 14 | public static void main(String[] args) throws InterruptedException, ExecutionException { 15 | // 1.创建服务引用对象实例 16 | ReferenceConfig referenceConfig = new ReferenceConfig(); 17 | // 2.设置应用程序信息 18 | referenceConfig.setApplication(new ApplicationConfig("first-dubbo-consumer")); 19 | // 3.设置服务注册中心 20 | referenceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); 21 | 22 | // 4.设置服务接口和超时时间 23 | referenceConfig.setInterface(GreetingService.class); 24 | referenceConfig.setTimeout(5000); 25 | 26 | // 5.设置服务分组与版本 27 | referenceConfig.setVersion("1.0.0"); 28 | referenceConfig.setGroup("dubbo"); 29 | 30 | // 6. 设置为异步 31 | referenceConfig.setAsync(true); 32 | 33 | // 7.引用服务 34 | GreetingService greetingService = referenceConfig.get(); 35 | 36 | // 8.异步执行,并设置回调 37 | System.out.println(greetingService.sayHello("hello")); 38 | CompletableFuture future1 = RpcContext.getContext().getCompletableFuture(); 39 | future1.whenComplete((v, t) -> { 40 | if (t != null) { 41 | t.printStackTrace(); 42 | } else { 43 | System.out.println(Thread.currentThread().getName() + " " + v); 44 | } 45 | 46 | }); 47 | 48 | // 9.异步执行,并设置回调 49 | System.out.println(greetingService.sayHello("jiaduo")); 50 | CompletableFuture future2 = RpcContext.getContext().getCompletableFuture(); 51 | future2.whenComplete((v, t) -> { 52 | if (t != null) { 53 | t.printStackTrace(); 54 | } else { 55 | System.out.println(Thread.currentThread().getName() + " " + v); 56 | } 57 | 58 | }); 59 | 60 | // 10. 挂起线程 61 | Thread.currentThread().join(); 62 | } 63 | } -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/CompletableFuture/TestCompletableFutureModelAsync.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter.CompletableFuture; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ExecutionException; 5 | import java.util.concurrent.LinkedBlockingQueue; 6 | import java.util.concurrent.ThreadPoolExecutor; 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.concurrent.TimeoutException; 9 | import java.util.function.BiConsumer; 10 | import java.util.function.Supplier; 11 | 12 | public class TestCompletableFutureModelAsync { 13 | // 0自定义线程池 14 | private final static int AVALIABLE_PROCESSORS = Runtime.getRuntime().availableProcessors(); 15 | private final static ThreadPoolExecutor POOL_EXECUTOR = new ThreadPoolExecutor(AVALIABLE_PROCESSORS, 16 | AVALIABLE_PROCESSORS * 2, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(5), 17 | new ThreadPoolExecutor.CallerRunsPolicy()); 18 | 19 | public static CompletableFuture runAsync(Runnable runnable) { 20 | CompletableFuture future = new CompletableFuture(); 21 | 22 | // 2.开启线程计算任务结果,并设置 23 | POOL_EXECUTOR.execute(() -> { 24 | 25 | // 2.1休眠3s,模拟任务计算 26 | try { 27 | runnable.run(); 28 | future.complete(null); 29 | 30 | } catch (Exception e) { 31 | future.completeExceptionally(e); 32 | } 33 | }); 34 | 35 | return future; 36 | } 37 | 38 | public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException { 39 | 40 | // 1.创建一个CompletableFuture对象 41 | CompletableFuture future = runAsync(new Runnable() { 42 | 43 | @Override 44 | public void run() { 45 | 46 | try { 47 | Thread.sleep(3000); 48 | } catch (InterruptedException e) { 49 | // TODO Auto-generated catch block 50 | e.printStackTrace(); 51 | } 52 | 53 | System.out.println("hello"); 54 | 55 | } 56 | }); 57 | 58 | future.whenComplete(new BiConsumer() { 59 | 60 | @Override 61 | public void accept(String t, Throwable u) { 62 | 63 | if (null == u) { 64 | System.out.println(t); 65 | } else { 66 | System.out.println(u.getLocalizedMessage()); 67 | 68 | } 69 | } 70 | }); 71 | 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /dubbo-demo/Provider/src/main/java/com/books/dubbo/demo/provider/APiConsumerInJvm.java: -------------------------------------------------------------------------------- 1 | package com.books.dubbo.demo.provider; 2 | 3 | import org.apache.dubbo.config.ApplicationConfig; 4 | import org.apache.dubbo.config.ReferenceConfig; 5 | import org.apache.dubbo.config.RegistryConfig; 6 | import org.apache.dubbo.config.ServiceConfig; 7 | import org.apache.dubbo.rpc.RpcContext; 8 | 9 | import com.books.dubbo.demo.api.GreetingService; 10 | import com.books.dubbo.demo.provider.GreetingServiceImpl; 11 | 12 | public class APiConsumerInJvm { 13 | 14 | static public void exportService() { 15 | // 1.创建ServiceConfig实例 16 | ServiceConfig serviceConfig = new ServiceConfig(); 17 | // 2.设置应用程序配置 18 | serviceConfig.setApplication(new ApplicationConfig("first-dubbo-provider")); 19 | 20 | // 3.设置服务注册中心信息 21 | RegistryConfig registryConfig = new RegistryConfig("zookeeper://127.0.0.1:2181"); 22 | serviceConfig.setRegistry(registryConfig); 23 | // 4.设置接口与实现类 24 | serviceConfig.setInterface(GreetingService.class); 25 | serviceConfig.setRef(new GreetingServiceImpl()); 26 | 27 | // 5.设置服务分组与版本 28 | serviceConfig.setVersion("1.0.0"); 29 | serviceConfig.setGroup("dubbo"); 30 | 31 | // 6.设置线程池策略 32 | 33 | // 7.导出服务 34 | serviceConfig.export(); 35 | 36 | // 8.挂起线程,避免服务停止 37 | System.out.println("server is started"); 38 | } 39 | 40 | static public void referService() { 41 | // 10.创建服务引用对象实例 42 | ReferenceConfig referenceConfig = new ReferenceConfig(); 43 | // 12.设置服务注册中心 44 | referenceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); 45 | 46 | // 13.设置服务接口和超时时间 47 | referenceConfig.setInterface(GreetingService.class); 48 | referenceConfig.setTimeout(5000); 49 | referenceConfig.setAsync(true); 50 | 51 | referenceConfig.setVersion("1.0.0"); 52 | referenceConfig.setGroup("dubbo"); 53 | referenceConfig.setCheck(false); 54 | 55 | // 16.引用服务 56 | GreetingService greetingService = referenceConfig.get(); 57 | 58 | // 17. 设置隐式参数 59 | RpcContext.getContext().setAttachment("company", "alibaba"); 60 | 61 | // 18调用服务 62 | System.out.println(greetingService.sayHello("world")); 63 | } 64 | 65 | public static void main(String[] args) throws InterruptedException { 66 | // 导出服务 67 | exportService(); 68 | 69 | // 引用服务 70 | referService(); 71 | 72 | Thread.currentThread().join(); 73 | } 74 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # 《Java异步编程实战》 3 | 4 | 作者:翟陆续(加多),某大型互联网公司资深开发工程师,并发编程网编辑;热衷并发编程,微服务架构设计,中间件基础设施,著作[《深度剖析Apache Dubbo技术内幕》](https://github.com/zhailuxu/Dubbo-Demo/blob/master/README.md)、[《Java并发编程之美》](https://github.com/zhailuxu/concurrent-program-demo/blob/master/README.md)、[《Java异步编程实战》](https://github.com/zhailuxu/async-program-demo/blob/master/README.md) ,微信公众号:技术原始积累。 5 | 6 | ## 0.1为何写作本书 7 | 8 | 异步编程是可以让程序并行运行的一种手段,其可以让程序中的一个工作单元与主应用程序线程分开独立运行,使用它有许多好处,例如可以提高应用程序的性能和响应能力。 9 | 10 | 虽然Java中不同技术域提供了相应的异步编程技术,但是对异步编程技术的描述散落到了不同技术域的技术文档中,并没有一个统一的地方对这些技术进行梳理归纳。另外这些技术之间是什么关系,各自的出现都是为了解决什么问题,我们也很难找到资料来解释。 11 | 12 | 本书的出现则是为了打破这种局面,本书旨在把Java中相关的异步编程技术进行归纳分类总结,然后呈现给大家,让大家可以有一个统一的地方来查看与探究。 13 | 14 | ## 0.2本书特色 15 | 本书涵盖了Java中常见的异步编程场景,这包含单JVM内的异步编程、以及跨主机通过网络通讯的远程过程调用的异步调用与异步处理、以及Web请求的异步处理等等。 16 | 17 | 本书在讲解Java中每种异步编程技术时都附有案例,以便理论与实践进行结合。 18 | 19 | 本书在讲解每种异步编程技术时大多都会对其实现原理进行讲解,以便让读者知其然也知其所以然。 20 | 21 | 本书对最近比较火的反应式编程以及WebFlux的使用与原理解析有一定深入的探索。 22 | 23 | ## 0.3 本书读者对象 24 | 本书适用于有一定Java编程基础,并对Java并发编程、Java异步编程、反应式编程感兴趣的读者。 25 | 26 | ## 0.4 如何阅读本书 27 | 对于初学者,建议按照本书编写的章节顺序进行学习,因为本书是按照从简到难的顺序编写的,并且每章都有一些代码示例让大家可以动手实践,以便加深理解。如何你对Java并发编程与异步编程有一定的基础,那么你可以直接从目录查看感兴趣的章节进行学习。本书总共分为9个章节,内容如下: 28 | 29 | - 第一章主要讲解异步编程的概念和作用,以及在日常开发中都有哪些异步编程的场景; 30 | 31 | - 第二章则讲解最基础的显示使用线程和线程池来实现异步编程,以及其存在的缺点; 32 | 33 | - 第三章内容比较丰富,主要讲解JDK中的各种Future,包含如何使用Future实现异步编程,以及其内部实现原理,最后讲解了如何结合JDK8 Stream 和Future实现异步编程; 34 | 35 | - 第四章讲解Spring框架中提供的异步执行能力,包含Spring中如何对TaskExecutor进行的抽象,以及如何使用注解@Async实现异步编程,以及其内部实现原理; 36 | 37 | - 第五章讲解比较火的反应式编程相关,包含什么是反应式编程,以及如何使用反应式编程规范的实现库RxJava和Reactor库实现异步编程; 38 | 39 | - 第六章讲解Web Servlet的异步非阻塞处理,这包含Servlet3.0规范如何提供异步处理能力的,以及Servlet3.1规范如何解决IO阻塞问题的,以及Spring MVC中如何使用异步处理能力; 40 | 41 | - 第七章讲解与Servlet技术栈并行存在的有Spring5.0提出来的Spring WebFlux的异步非阻塞处理,包含Spring WebFlux的由来、Spring WebFlux的并发模型、两种编程模型,以及如何使用Spring WebFlux来进行服务开发,Spring WebFlux内部实现原理是怎样的; 42 | 43 | - 第八章则概要介绍了业界为方便实现异步编程而设计的一些框架和中间件,这包含异步、基于事件驱动的网络编程框架Netty、高性能RPC框架Apache Dubbo、高性能线程间消息传递库Disruptor、异步基于事件驱动的编程框架-Akka、高性能分布式消息平台-Apache RocketMq ; 44 | 45 | - 第九章则介绍新兴的Golang语言如何从语言层面提供了强大的异步编程能力。 46 | 47 | 48 | ## 0.5 资源和勘误 49 | 大家可以到https://github.com/zhailuxu/async-program-demo 下载本书的demo资源,另外由于笔者水平有限,如果您在阅读本书时候发现错误,可以关注微信公众号:技术原始积累 ,留言反馈。 50 | 51 | ## 0.6 购买 52 | - [京东](https://item.jd.com/12778422.html) 53 | 54 | ## 0.7 更多新书,关注下面微信公众号 55 | 56 | 57 | ![image]( https://zhailuxu.github.io/assets/images/jiaduowechat.png) 58 | 59 | 60 | ## 0.7 我的网站 61 | https://zhailuxu.github.io/ 62 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/netty/RpcServer.java: -------------------------------------------------------------------------------- 1 | package org.Chapter8.netty; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.buffer.ByteBuf; 5 | import io.netty.buffer.Unpooled; 6 | import io.netty.channel.ChannelFuture; 7 | import io.netty.channel.ChannelHandler; 8 | import io.netty.channel.ChannelInitializer; 9 | import io.netty.channel.ChannelOption; 10 | import io.netty.channel.ChannelPipeline; 11 | import io.netty.channel.EventLoopGroup; 12 | import io.netty.channel.nio.NioEventLoopGroup; 13 | import io.netty.channel.socket.SocketChannel; 14 | import io.netty.channel.socket.nio.NioServerSocketChannel; 15 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 16 | import io.netty.handler.codec.string.StringDecoder; 17 | import io.netty.handler.codec.string.StringEncoder; 18 | import io.netty.handler.logging.LogLevel; 19 | import io.netty.handler.logging.LoggingHandler; 20 | 21 | /** 22 | * 服务端 23 | */ 24 | public final class RpcServer { 25 | public static void main(String[] args) throws Exception { 26 | // 0.配置创建两级线程池 27 | EventLoopGroup bossGroup = new NioEventLoopGroup(1);// boss 28 | EventLoopGroup workerGroup = new NioEventLoopGroup();// worker 29 | // 1.创建业务处理hander 30 | NettyServerHandler servrHandler = new NettyServerHandler(); 31 | try { 32 | ServerBootstrap b = new ServerBootstrap(); 33 | b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100) 34 | .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer() { 35 | @Override 36 | public void initChannel(SocketChannel ch) throws Exception { 37 | ChannelPipeline p = ch.pipeline(); 38 | // 1.1设置帧分隔符解码器 39 | ByteBuf delimiter = Unpooled.copiedBuffer("|".getBytes()); 40 | p.addLast(new DelimiterBasedFrameDecoder(1000, delimiter)); 41 | // 1.2设置消息内容自动转换为String的解码器到管线 42 | p.addLast(new StringDecoder()); 43 | // 1.3设置字符串消息自动进行编码的编码器到管线 44 | p.addLast(new StringEncoder()); 45 | // 1.4添加业务hander到管线 46 | p.addLast(servrHandler); 47 | } 48 | }); 49 | 50 | // 2.启动服务,并且在12800端口监听 51 | ChannelFuture f = b.bind(12800).sync(); 52 | 53 | // 3. 等待服务监听套接字关闭 54 | f.channel().closeFuture().sync(); 55 | } finally { 56 | // 4.优雅关闭两级线程池,以便释放线程 57 | bossGroup.shutdownGracefully(); 58 | workerGroup.shutdownGracefully(); 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /dubbo-demo/Consumer/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 4.0.0 7 | 8 | com.books.dubbo.demo 9 | Demo 10 | 0.0.1-SNAPSHOT 11 | 12 | com.books.dubbo.demo 13 | Consumer 14 | 0.0.1-SNAPSHOT 15 | Consumer 16 | http://maven.apache.org 17 | 18 | UTF-8 19 | 20 | 21 | 22 | 23 | mysql 24 | mysql-connector-java 25 | 8.0.16 26 | 27 | 28 | 29 | 30 | com.oracle 31 | ojdbc6 32 | 11.2.0.3 33 | 34 | 35 | 36 | com.books.dubbo.demo 37 | Sdk 38 | 0.0.1-SNAPSHOT 39 | 40 | 41 | junit 42 | junit 43 | 3.8.1 44 | test 45 | 46 | 47 | 48 | 49 | com.google.guava 50 | guava 51 | 27.0-jre 52 | 53 | 54 | 55 | com.101tec 56 | zkclient 57 | 0.10 58 | 59 | 60 | slf4j-log4j12 61 | org.slf4j 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | org.apache.maven.plugins 71 | maven-compiler-plugin 72 | 3.6.0 73 | 74 | 1.8 75 | 1.8 76 | 77 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /dubbo-demo/Sdk/src/main/java/com/books/dubbo/demo/test/performance/TestConsumerPerformance.java: -------------------------------------------------------------------------------- 1 | 2 | package com.books.dubbo.demo.test.performance; 3 | 4 | import java.util.UUID; 5 | 6 | import org.apache.dubbo.config.ApplicationConfig; 7 | import org.apache.dubbo.config.ReferenceConfig; 8 | import org.apache.dubbo.config.RegistryConfig; 9 | import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient; 10 | import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext; 11 | import org.apache.jmeter.samplers.SampleResult; 12 | 13 | import com.books.dubbo.demo.api.GreetingService; 14 | 15 | public class TestConsumerPerformance extends AbstractJavaSamplerClient { 16 | 17 | private GreetingService greetingService; 18 | 19 | @Override 20 | public SampleResult runTest(JavaSamplerContext arg0) { 21 | 22 | System.out.println("---begin run----"); 23 | // 0.结果对象 24 | SampleResult sr = new SampleResult(); 25 | 26 | String result = null; 27 | // 1.启动测试 28 | try { 29 | 30 | // 1.1开启样本测试 31 | sr.sampleStart(); 32 | // 1.2发起远程调用 33 | result = greetingService.sayHello(UUID.randomUUID().toString()); 34 | // 1.3设置响应结果哦哦 35 | sr.setResponseData("from provider:" + result, null); 36 | sr.setDataType(SampleResult.TEXT); 37 | sr.setSuccessful(true); 38 | 39 | // 1.4关闭样本测试 40 | sr.sampleEnd(); 41 | } catch (Exception e) { 42 | e.printStackTrace(); 43 | } 44 | 45 | System.out.println("---end run----" + result); 46 | // 2.返回结果 47 | return sr; 48 | } 49 | 50 | // 创建引入实例 51 | @Override 52 | public void setupTest(JavaSamplerContext context) { 53 | 54 | try { 55 | // 0.创建服务引用对象实例 56 | ReferenceConfig referenceConfig = new ReferenceConfig(); 57 | // 1.设置应用程序信息 58 | referenceConfig.setApplication(new ApplicationConfig("first-dubbo-consumer")); 59 | // 2.设置服务注册中心 60 | referenceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); 61 | // 3.设置服务接口和超时时间 62 | referenceConfig.setInterface(GreetingService.class); 63 | referenceConfig.setTimeout(5000); 64 | // 4.设置自定义负载均衡策略与集群容错策略 65 | 66 | // 5.设置服务分组与版本 67 | referenceConfig.setVersion("1.0.0"); 68 | referenceConfig.setGroup("dubbo"); 69 | 70 | // 6.引用服务 71 | greetingService = referenceConfig.get(); 72 | 73 | // 76调用服务 74 | System.out.println("get referenc ok "); 75 | }catch(Exception e) { 76 | System.out.println(e.getLocalizedMessage()); 77 | 78 | } 79 | 80 | } 81 | 82 | public static void main(String[] ar) { 83 | TestConsumerPerformance test = new TestConsumerPerformance(); 84 | test.setupTest(null); 85 | test.runTest(null); 86 | 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /async-program-demo/Chapter8/src/main/java/org/Chapter8/netty/NettyServerHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 The Netty Project 3 | * 4 | * The Netty Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package org.Chapter8.netty; 17 | 18 | import io.netty.channel.ChannelHandler.Sharable; 19 | 20 | 21 | import io.netty.buffer.Unpooled; 22 | import io.netty.channel.ChannelHandlerContext; 23 | import io.netty.channel.ChannelInboundHandlerAdapter; 24 | 25 | /** 26 | * Handler implementation for the echo server. 27 | */ 28 | @Sharable 29 | public class NettyServerHandler extends ChannelInboundHandlerAdapter { 30 | 31 | // 根据消息内容和请求id,拼接消息帧 32 | public String generatorFrame(String msg, String reqId) { 33 | return msg + ":" + reqId + "|"; 34 | } 35 | 36 | @Override 37 | public void channelRead(ChannelHandlerContext ctx, Object msg) { 38 | 39 | // 异步,释放IO线程 40 | AllChannelHandler.channelRead(() -> { 41 | try { 42 | System.out.println(msg); 43 | // 1.获取消息体,并且解析出请求id 44 | String str = (String) msg; 45 | String reqId = str.split(":")[1]; 46 | 47 | // 2.拼接结果,请求id,协议帧分隔符(模拟服务端执行服务产生结果) 48 | String resp = generatorFrame("im jiaduo ", reqId); 49 | 50 | try { 51 | Thread.sleep(2000); 52 | } catch (InterruptedException e) { 53 | e.printStackTrace(); 54 | } 55 | 56 | // 3.写回结果 57 | ctx.channel().writeAndFlush(Unpooled.copiedBuffer(resp.getBytes())); 58 | } catch (Exception e) { 59 | e.printStackTrace(); 60 | } 61 | }); 62 | } 63 | 64 | @Override 65 | public void channelReadComplete(ChannelHandlerContext ctx) { 66 | } 67 | 68 | @Override 69 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 70 | cause.printStackTrace(); 71 | ctx.close(); 72 | } 73 | 74 | @Override 75 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 76 | System.out.println("------in active----"); 77 | ctx.fireChannelInactive(); 78 | } 79 | 80 | @Override 81 | public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { 82 | System.out.println("------handlerRemoved----"); 83 | super.handlerRemoved(ctx); 84 | 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/CompletableFuture/TestMoreCompletableFuture.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter.CompletableFuture; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.CompletableFuture; 6 | import java.util.concurrent.ExecutionException; 7 | import java.util.function.Function; 8 | import java.util.function.Supplier; 9 | import java.util.stream.Collectors; 10 | 11 | public class TestMoreCompletableFuture { 12 | 13 | // 1.异步任务,返回future 14 | public static CompletableFuture doSomethingOne(String id) { 15 | // 1.1创建异步任务 16 | return CompletableFuture.supplyAsync(new Supplier() { 17 | 18 | @Override 19 | public String get() { 20 | 21 | // 1.1.1休眠1s,模拟任务计算 22 | try { 23 | Thread.sleep(1000); 24 | } catch (InterruptedException e) { 25 | e.printStackTrace(); 26 | } 27 | System.out.println("compute " + id); 28 | 29 | return id; 30 | } 31 | }); 32 | } 33 | 34 | // 2.开启异步任务,返回future 35 | public static CompletableFuture doSomethingTwo(String id) { 36 | return CompletableFuture.supplyAsync(new Supplier() { 37 | 38 | @Override 39 | public String get() { 40 | 41 | // 2.1,休眠3s,模拟计算 42 | try { 43 | Thread.sleep(5000); 44 | } catch (InterruptedException e) { 45 | // TODO Auto-generated catch block 46 | e.printStackTrace(); 47 | } 48 | System.out.println("compute " + id); 49 | 50 | return id; 51 | } 52 | }); 53 | } 54 | 55 | public static void allOf() throws InterruptedException, ExecutionException { 56 | // 1.创建future列表 57 | List> futureList = new ArrayList<>(); 58 | futureList.add(doSomethingOne("1")); 59 | futureList.add(doSomethingOne("2")); 60 | futureList.add(doSomethingOne("3")); 61 | futureList.add(doSomethingOne("4")); 62 | 63 | // 2.转换多个future为一个 64 | CompletableFuture result = CompletableFuture 65 | .allOf(futureList.toArray(new CompletableFuture[futureList.size()])); 66 | 67 | // 3.等待所有future都完成 68 | System.out.println(result.get()); 69 | 70 | // 4.等所有future执行完毕后,获取所有future的计算结果 71 | CompletableFuture> finallyResult = result.thenApply(new Function>() { 72 | 73 | @Override 74 | public List apply(Void t) { 75 | return futureList.stream().map(future -> future.join()).collect(Collectors.toList()); 76 | } 77 | }); 78 | 79 | // 5.打印所有future的结果 80 | for (String str : finallyResult.get()) { 81 | System.out.println(str); 82 | } 83 | } 84 | 85 | public static void anyOf() throws InterruptedException, ExecutionException { 86 | // 1.创建future列表 87 | List> futureList = new ArrayList<>(); 88 | futureList.add(doSomethingOne("1")); 89 | futureList.add(doSomethingOne("2")); 90 | futureList.add(doSomethingTwo("3")); 91 | 92 | // 2.转换多个future为一个 93 | CompletableFuture result = CompletableFuture 94 | .anyOf(futureList.toArray(new CompletableFuture[futureList.size()])); 95 | 96 | // 3.等待某一个future完成 97 | System.out.println(result.get()); 98 | 99 | } 100 | 101 | public static void main(String[] args) throws InterruptedException, ExecutionException { 102 | // 1.allOf 103 | allOf(); 104 | 105 | // 2.anyOf 106 | // anyOf(); 107 | 108 | Thread.sleep(10000); 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /async-program-demo/Third-Chapter/src/main/java/org/Third/Chapter/CompletableFuture/TestFutureException.java: -------------------------------------------------------------------------------- 1 | package org.Third.Chapter.CompletableFuture; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.concurrent.ExecutionException; 5 | import java.util.concurrent.TimeUnit; 6 | import java.util.concurrent.TimeoutException; 7 | import java.util.function.Supplier; 8 | 9 | public class TestFutureException { 10 | 11 | public static void one() throws InterruptedException, ExecutionException { 12 | // 1.创建一个CompletableFuture对象 13 | CompletableFuture future = new CompletableFuture(); 14 | 15 | // 2.开启线程计算任务结果,并设置 16 | new Thread(() -> { 17 | 18 | // 2.1休眠3s,模拟任务计算 19 | try { 20 | Thread.sleep(3000); 21 | } catch (InterruptedException e) { 22 | // TODO Auto-generated catch block 23 | e.printStackTrace(); 24 | } 25 | // 2.2设置计算结果到future 26 | System.out.println("----" + Thread.currentThread().getName() + " set future result----"); 27 | future.completeExceptionally(new RuntimeException("error exception")); 28 | 29 | }, "thread-1").start(); 30 | 31 | // 3.等待计算结果 32 | System.out.println("---main thread wait future result---"); 33 | System.out.println(future.get()); 34 | // System.out.println(future.get(1000,TimeUnit.MILLISECONDS)); 35 | System.out.println("---main thread got future result---"); 36 | } 37 | 38 | public static void two() throws InterruptedException, ExecutionException { 39 | // 1.创建一个CompletableFuture对象 40 | CompletableFuture future = new CompletableFuture(); 41 | 42 | // 2.开启线程计算任务结果,并设置 43 | new Thread(() -> { 44 | 45 | // 2.1休眠3s,模拟任务计算 46 | try { 47 | Thread.sleep(3000); 48 | } catch (InterruptedException e) { 49 | // TODO Auto-generated catch block 50 | e.printStackTrace(); 51 | } 52 | // 2.2设置计算结果到future 53 | System.out.println("----" + Thread.currentThread().getName() + " set future result----"); 54 | future.completeExceptionally(new RuntimeException("error exception")); 55 | 56 | }, "thread-1").start(); 57 | ; 58 | // 3.等待计算结果 59 | System.out.println("---main thread wait future result---"); 60 | System.out.println(future.exceptionally(t -> "default").get());// 默认值 61 | // System.out.println(future.get(1000,TimeUnit.MILLISECONDS)); 62 | System.out.println("---main thread got future result---"); 63 | } 64 | 65 | public static void two1() throws InterruptedException, ExecutionException { 66 | // 1.创建一个CompletableFuture对象 67 | CompletableFuture future = new CompletableFuture(); 68 | 69 | // 2.开启线程计算任务结果,并设置 70 | new Thread(() -> { 71 | 72 | // 2.1休眠3s,模拟任务计算 73 | try { 74 | Thread.sleep(3000); 75 | } catch (InterruptedException e) { 76 | // TODO Auto-generated catch block 77 | e.printStackTrace(); 78 | } 79 | // 2.2设置计算结果到future 80 | System.out.println("----" + Thread.currentThread().getName() + " set future result----"); 81 | future.completeExceptionally(new RuntimeException("error exception")); 82 | 83 | }, "thread-1").start(); 84 | ; 85 | 86 | // 3.等待计算结果 87 | System.out.println("---main thread wait future result---"); 88 | System.out.println(future.exceptionally(t -> "default").get());// 默认值 89 | // System.out.println(future.get(1000,TimeUnit.MILLISECONDS)); 90 | System.out.println("---main thread got future result---"); 91 | } 92 | 93 | public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException { 94 | 95 | two(); 96 | } 97 | } 98 | --------------------------------------------------------------------------------