實戰學習掌握ignite技術運用03

ignite-example

這是一篇引導初學者如何使用ignite技術的實戰指導,可能好多高級沒有走過也可以用來參考,繼續深入學習ignite技術運用。

掌握這個樣例,可以說ignite入門了! 後續的進階要在實戰中積累,如springdata結合使用、集羣維護等。

準備

下載apache-ignite-2.9.1-bin.zip

下載ignite2.9.1版本的zip,本地解壓即可,然後將default-config.xml文件修改爲如下配置(同example配置一致)。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/util
       http://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="grid.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
    <property name="peerClassLoadingEnabled" value="true"/>
        <property name="includeEventTypes">
            <list>
                <util:constant static-field="org.apache.ignite.events.EventType.EVT_TASK_STARTED"/>
                <util:constant static-field="org.apache.ignite.events.EventType.EVT_TASK_FINISHED"/>
                <util:constant static-field="org.apache.ignite.events.EventType.EVT_TASK_FAILED"/>
                <util:constant static-field="org.apache.ignite.events.EventType.EVT_TASK_TIMEDOUT"/>
                <util:constant static-field="org.apache.ignite.events.EventType.EVT_TASK_SESSION_ATTR_SET"/>
                <util:constant static-field="org.apache.ignite.events.EventType.EVT_TASK_REDUCED"/>
                <util:constant static-field="org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_PUT"/>
                <util:constant static-field="org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_READ"/>
                <util:constant static-field="org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_REMOVED"/>
            </list>
        </property>
        <property name="discoverySpi">
            <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
                <property name="ipFinder">
                    <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder">
                        <property name="addresses">
                            <list>
                                <value>127.0.0.1:47500..47509</value>
                            </list>
                        </property>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
</beans>

最後直接啓動 $ ./ignite.sh -v 即可,端口會自動分配,不用修改其他。

下載ignite-example用例

1、在apache-ignite-2.9.1-bin.zip包解壓後的examples目錄裏面就是,可以直接複製出了用。點擊下載

2、下載apache-ignite-2.9.1-src.zip解壓後的example目錄就是,這個是代test樣例代碼的。點擊下載

3、下載我的樣例ignite-example。點擊下載

代碼下載後使用idea的maven把jar下載後complie即可運行,這裏需要注意配置文件的訪問路徑需要修改,不然起不來(因爲examples的上下文在copy建立新工程時改變了,我的測試中是沒有examples目錄的)。

樣例工程介紹

樣例覆蓋範圍涵蓋了ignite所能支持的所有場景,下面ClusterGroup和Events樣例運行需要啓動兩個ignite節點進行配合。

ClusterGroupExample

    public static void main(String[] args) throws IgniteException {
        try (Ignite ignite = Ignition.start("./config/example-ignite.xml")) {
            if (!ExamplesUtils.checkMinTopologySize(ignite.cluster(), 2))
                return;

            System.out.println();
            System.out.println("Compute example started.");

            IgniteCluster cluster = ignite.cluster();

            // Say hello to all nodes in the cluster, including local node.
            sayHello(ignite, cluster);

            // Say hello to all remote nodes.
            sayHello(ignite, cluster.forRemotes());

            // Pick random node out of remote nodes.
            ClusterGroup randomNode = cluster.forRemotes().forRandom();

            // Say hello to a random node.
            sayHello(ignite, randomNode);

            // Say hello to all nodes residing on the same host with random node.
            sayHello(ignite, cluster.forHost(randomNode.node()));

            // Say hello to all nodes that have current CPU load less than 50%.
            sayHello(ignite, cluster.forPredicate(n -> n.metrics().getCurrentCpuLoad() < 0.5));
        }
    }

    /**
     * Print 'Hello' message on remote nodes.
     *
     * @param ignite Ignite.
     * @param grp Cluster group.
     * @throws IgniteException If failed.
     */
    private static void sayHello(Ignite ignite, final ClusterGroup grp) throws IgniteException {
        // Print out hello message on all cluster nodes.
        ignite.compute(grp).broadcast(
            () -> System.out.println(">>> Hello Node: " + grp.ignite().cluster().localNode().id()));
    }

EventsExample

    public static void main(String[] args) throws Exception {
        try (Ignite ignite = Ignition.start("./config/example-ignite.xml")) {
            System.out.println();
            System.out.println(">>> Events API example started.");

            // Listen to events happening on local node.
            localListen();

            // Listen to events happening on all cluster nodes.
            remoteListen();

            // Wait for a while while callback is notified about remaining puts.
            Thread.sleep(1000);
        }
    }

    /**
     * Listen to events that happen only on local node.
     *
     * @throws IgniteException If failed.
     */
    private static void localListen() throws IgniteException {
        System.out.println();
        System.out.println(">>> Local event listener example.");

        Ignite ignite = Ignition.ignite();

        IgnitePredicate<TaskEvent> lsnr = evt -> {
            System.out.println("Received task event [evt=" + evt.name() + ", taskName=" + evt.taskName() + ']');

            return true; // Return true to continue listening.
        };

        // Register event listener for all local task execution events.
        ignite.events().localListen(lsnr, EVTS_TASK_EXECUTION);

        // Generate task events.
        ignite.compute().withName("example-event-task").run(() -> System.out.println("Executing sample job."));

        // Unsubscribe local task event listener.
        ignite.events().stopLocalListen(lsnr);
    }

    /**
     * Listen to events coming from all cluster nodes.
     *
     * @throws IgniteException If failed.
     */
    private static void remoteListen() throws IgniteException {
        System.out.println();
        System.out.println(">>> Remote event listener example.");

        // This optional local callback is called for each event notification
        // that passed remote predicate listener.
        IgniteBiPredicate<UUID, TaskEvent> locLsnr = (nodeId, evt) -> {
            // Remote filter only accepts tasks whose name being with "good-task" prefix.
            assert evt.taskName().startsWith("good-task");

            System.out.println("Received task event [evt=" + evt.name() + ", taskName=" + evt.taskName());

            return true; // Return true to continue listening.
        };

        // Remote filter which only accepts tasks whose name begins with "good-task" prefix.
        IgnitePredicate<TaskEvent> rmtLsnr = evt -> evt.taskName().startsWith("good-task");

        Ignite ignite = Ignition.ignite();

        // Register event listeners on all nodes to listen for task events.
        ignite.events().remoteListen(locLsnr, rmtLsnr, EVTS_TASK_EXECUTION);

        // Generate task events.
        for (int i = 0; i < 10; i++) {
            ignite.compute().withName(i < 5 ? "good-task-" + i : "bad-task-" + i).run(new IgniteRunnable() {
                // Auto-inject task session.
                @TaskSessionResource
                private ComputeTaskSession ses;

                @Override public void run() {
                    System.out.println("Executing sample job for task: " + ses.getTaskName());
                }
            });
        }
    }

樣例運行

項目編譯中遇到maven的jar下載不了可更換鏡像倉庫到阿里的私服。用例運行屬於傳統java的application體系,直接run main方法即可。

這些用例寫的非常實用,結構簡單清晰,真的apache的水準。他們推一個新技術思考的非常全面,就比如doc和example,清晰還全面讓人一看就懂。這樣最大的好處技術使用成本非常低,和國內很多公司推廣開源技術相比,大巫見小巫啊。

作者:Owen Jia

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章