1.guava事件總線(AsyncEventBus)使用java
1.1引入依賴web
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>23.0</version> </dependency>
1.2在spring中經過配置類(支持spring4.x以上及springboot)使AsyncEventBus交給spring容器管理,並設置爲單例模式spring
package com.zy.eventbus;
import com.google.common.eventbus.AsyncEventBus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
* 事件注入中心
*/
@Configuration
public class AsynEventBusConfig {
@Bean
@Scope("singleton")
public AsyncEventBus asyncEventBus() {
final ThreadPoolTaskExecutor executor = executor();
return new AsyncEventBus(executor);
}
@Bean
public ThreadPoolTaskExecutor executor(){
/*
org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
private int corePoolSize = 1;
private int maxPoolSize = 2147483647;
private int queueCapacity = 2147483647;
private int keepAliveSeconds = 60;
private boolean allowCoreThreadTimeOut = false;
* */
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(100);
executor.setQueueCapacity(1000);
// executor.setKeepAliveSeconds(600);
// executor.setAllowCoreThreadTimeOut(true);
return executor;
}
}
1.3在須要異步執行的類中註冊該類,並給異步執行的方法上加@Subscribe註解安全
package com.zy.service.impl; import com.google.common.eventbus.AllowConcurrentEvents; import com.google.common.eventbus.AsyncEventBus; import com.google.common.eventbus.Subscribe;import com.zy.service.StuServiceI; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; @Service("stuService") public class StuServiceImpl implements StuServiceI { @Autowired private AsyncEventBus asyncEventBus; @PostConstruct // 註冊該類 public void register(){ asyncEventBus.register(this); } @AllowConcurrentEvents//線程安全 @Subscribe // 異步執行的方法標識:須要傳入String類型參數 public void async01(String str){ System.out.println(str); } }
1.4調用方法的類springboot
package com.zy.controller; import com.google.common.eventbus.AsyncEventBus; import com.zy.service.StuServiceI; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping public class GuavaEventBusController { @Autowired private AsyncEventBus eventBus; @GetMapping("/eventbus") public String eventbus(){ System.out.println("hello"); eventBus.post("bbb"); // 調用執行方法的參數 System.out.println("world"); return "hello eventbus"; } }