SpringBoot项目中使用Google EventBus

SpringBoot项目中使用Google EventBus

1、项目导入依赖

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>20.0</version>
</dependency>

2、注册为Bean组件

package com.jidi.springbootredis.config;

import com.google.common.eventbus.AsyncEventBus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author jidi
 * @Email jidi_jidi@163.com
 * @Date 2021/5/20
 */

@Configuration
public class EventBusConfig {

    /**
     * 定义EventBus
     */
    @Bean
    public AsyncEventBus asyncEventBus() {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 10, 60,TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), new ThreadPoolExecutor.DiscardPolicy());
        return new AsyncEventBus(threadPoolExecutor);
    }
}

3、添加事件处理监听器

package com.jidi.springbootredis.listener;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.Subscribe;
import com.jidi.springbootredis.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

/**
 * @Description
 * @Author jidi
 * @Email jidi_jidi@163.com
 * @Date 2021/5/20
 */

@Slf4j
@Component
public class EventBusListener {

    @Autowired
    private AsyncEventBus eventBus;


    /**
     *  在事件总线中注册
     */
    @PostConstruct
    public void init(){
        eventBus.register(this);
    }



    /**
     *  具体要执行的业务逻辑
     */
    @Subscribe
    public void test(User user){
        log.info("{}", user.toString());
    }
}

4、业务层调用

    @Autowired
    private EventBus eventBus;


    /**
     * 使用EventBus进行异步处理,会执行EventBusListener中对应的方法,根据参数类型进行匹配
     */
    public void test(){
        eventBus.post(new User());
    }
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值