google中guava类库:AsyncEventBus

在spring中通过配置类(支持spring4.x以上及springboot)使AsyncEventBus交给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调用方法的类

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";
    }
}

转载:https://www.cnblogs.com/psy-code/p/9788213.html

你可能感兴趣的:(#,Guava)