目录

扩展 bugu-mongo

优质
小牛编辑
127浏览
2023-12-01

bugu-mongo是基于微内核(Microkernel)架构的,其核心是bugu-mongo-core模块,可以在这个核心模块上进行扩展。

实际上,bugu-mongo-cache、bugu-mongo-fs、bugu-mongo-lucene等模块,都是基于core模块的扩展。

原理

所有的数据库操作(CRUD),都是由BuguDao来执行的,你可以往BuguDao里添加监听器(EntityListener),当BuguDao执行CRUD操作时,会以事件的形式通知所有的监听器。

EntityListener是一个接口,其定义如下:

public interface EntityListener {

    /**
     * Notified that an entity has been inserted.
     * @param entity the inserted object
     */
    public void entityInserted(BuguEntity entity);

    /**
     * Notified that an entity has been updated.
     * @param entity the updated object
     */
    public void entityUpdated(BuguEntity entity);

    /**
     * Notified that an entity has been deleted.
     * @param entity the deleted object
     */
    public void entityDeleted(BuguEntity entity);

}

监听器中的方法,是异步执行的,不会影响BuguDao的CRUD操作。bugu-mongo框架内有一个线程池,所有的监听器程序,都在这个线程池内执行。线程池的大小,默认是CPU个数*2 + 1。如果你要修改这个线程池的大小,请在BuguFramework建立数据库连接之前进行。如下:

BuguFramework framework = BuguFramework.getInstance();
framework.setThreadPoolSize(30);

BuguConnection conn = framework.createConnection();
conn.setHost("192.168.0.200");
conn.setPort(27017);
conn.setUsername("test");
conn.setPassword("test");
conn.setDatabase("test");
conn.connect();

示例

假设对于Foo实体,有对象被删除的时候,我们都需要在日志中记录下来。

步骤一:实现一个监听器

public class MyFooListener implements EntityListener {

    @Override
    public void entityInserted(BuguEntity entity) {
        //do nothing
    }

    @Override
    public void entityUpdated(BuguEntity entity) {
        //do nothing
    }

    @Override
    public void entityDeleted(BuguEntity entity) {
        System.out.println("entity has been deleted! id is: " + entity.getId());
    }

}

步骤二:往FooDao中添加监听器

public class FooDao extends BuguDao<Foo> {

    public FooDao(){
        super(Foo.class);
        super.addEntityListener(new MyFooListener());
    }

}

完成!