美文网首页
Basic of Event Listener

Basic of Event Listener

作者: coolala | 来源:发表于2020-09-10 13:21 被阅读0次

    When using event, better to have some basic conception : )

    Only say something on the top of my head, definitely will add more stuff later.

    Let's use MySQL binary log as example. We can use binary log to monitor row change in table. Once a new tuple is inserted, MySQL will generate an event. In order to get the event, we should use an event listener to catch it. Usually, all APIs have listeners for different events, such as insert_event, update_event, gtid_event etc.

    Before we use listener, we should register the listener in the specific API. Multiple event listeners can monitor same event.

    The most common way to implement a listener is to extends/implements a listener class/interface from API, here we use MySQL binlog connector API as an example.

    import com.github.shyiko.mysql.binlog.event*;
    ...
    void startEventListener() {
        client.registerEventListener(binLogEventListener);
        while(true){
            ...
            client.connect();
            ...
        }
    }
    ...
    private class BinLogEventListener implements BinaryLogClient.EventListener {
        ...
        @Override
        public void onEvent(Event event) {
            ...
            //whatever handler code
        }
    }
    

    About case is the explicit way to implement a listener.
    We can also implement it implicitly.

    import com.github.shyiko.mysql.binlog.event*;
    ...
    void startEventListener() {
        client.registerEventListener(this :: eventHandler);
        while(true){
            ...
            client.connect();
            ...
        }
    }
    ...
    public void eventHandler() {
        ...
        //whatever handler code
    }
    ...
    

    But please be careful, this :: eventHandler will create a new EventListener instance each time.

    My mentor just gave me a pretty good example to explain above "new instance case", let's be a copy cat : )

    import java.util.*;
    import java.util.concurrent.*;
    import java.util.function.*;
    
    public class test {
        public static void main (String[] args) {
            new Example();
        }
    }
    
    class Example {
        public Example() {
            acceptTestInterface(this::doTheThing);
            acceptTestInterface(this::doTheThing);
        }
        public void doTheThing() {
            //whatever
        }
        public void acceptTestInterface(Runnable x) {
            System.out.println("Identity" + System.identityHashCode(x));
        }
    }
    
    // we will get the result with two different hashcode.
    

    That's it, will update later >_<

    相关文章

      网友评论

          本文标题:Basic of Event Listener

          本文链接:https://www.haomeiwen.com/subject/axqpektx.html