google事件总线,实现进程内异步与解耦

Guava EventBus 异步消息传递
本文介绍了一个使用Google Guava库中的EventBus实现异步消息传递的示例。该示例展示了如何通过创建Producer和Consumer类来发送和接收消息,并使用线程池进行并发处理。

先直接上代码:

package com.liuxd.eventBus;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.SubscriberExceptionContext;
import com.google.common.eventbus.SubscriberExceptionHandler;

import javax.annotation.Resource;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Liuxd on 2018/8/16.
 */
public class Producer {

    private int maxPoolSize = 150;
    private AsyncEventBus sendMessEventBus;

    @Resource
    Consumer consumer = new Consumer();

    private ThreadPoolExecutor threadPoolExecutor;

    public static void main(String[] args) {
        Producer producer = new Producer();
        producer.init();

        System.out.println(producer.getCorePoolSize());
        for (int i = 0; i < 1000; i++) {
            System.out.println("当前剩余任务数:"+producer.getTaskCount());
            producer.post("消息体" + i);
        }
    }

//    @PostConstruct
    public void init() {
        threadPoolExecutor = newThreadPool();

        sendMessEventBus = new AsyncEventBus(threadPoolExecutor, new SubscriberExceptionHandler() {
            public void handleException(Throwable exception, SubscriberExceptionContext context) {
                exception.printStackTrace();
                System.out.println(exception.getMessage());
                System.out.println(exception.toString());
            }
        });
        sendMessEventBus.register(consumer);


    }

    public void post(String message) {
        sendMessEventBus.post(message);

    }

    private ThreadPoolExecutor newThreadPool() {
        return new ThreadPoolExecutor(maxPoolSize, maxPoolSize,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(200), new DefaultThreadFactory(), new RejectedExecutionHandler() {
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                //TODO
            }
        });
    }


    public void setCorePoolSize(int size) {
        threadPoolExecutor.setCorePoolSize(size);
        threadPoolExecutor.setMaximumPoolSize(size);
    }

    public int getCorePoolSize() {
        return threadPoolExecutor.getCorePoolSize();
    }

    public int getTaskCount() {
        return threadPoolExecutor.getQueue().size();
    }

    static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = "evnetbusPmpool-" +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

}

 

消费者---订阅者

package com.liuxd.eventBus;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;

import java.util.Random;

/**
 * 事件
 */

public class Consumer {

    /**
     * 处理事件触发
     */
    @Subscribe
    @AllowConcurrentEvents
    public void processor(String message) {
        myPrint(message);

    }


    private void myPrint(String message) {
        System.out.println("打印:"+message+"_当前线程id为:"+Thread.currentThread().getId());
    }

    public static void main(String[] args) {
        Consumer consumer = new Consumer();
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

春风化作秋雨

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值