国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Java工作隊列代碼詳解

Java工作隊列代碼詳解

2021-02-19 23:16mengwei Java教程

這篇文章主要介紹了Java工作隊列代碼詳解,涉及Round-robin 轉發,消息應答(messageacknowledgments),消息持久化(Messagedurability)等相關內容,具有一定參考價值,需要的朋友可以了解下。

我們寫了通過一個命名的隊列發送和接收消息,如果你還不了解請點擊:rabbitmqjava入門。這篇中我們將會創建一個工作隊列用來在工作者(consumer)間分發耗時任務。

工作隊列的主要任務是:避免立刻執行資源密集型任務,然后必須等待其完成。相反地,我們進行任務調度:我們把任務封裝為消息發送給隊列。工作進行在后臺運行并不斷的從隊列中取出任務然后執行。當你運行了多個工作進程時,任務隊列中的任務將會被工作進程共享執行。

這樣的概念在web應用中極其有用,當在很短的http請求間需要執行復雜的任務。

1、準備

我們使用thread.sleep來模擬耗時的任務。我們在發送到隊列的消息的末尾添加一定數量的點,每個點代表在工作線程中需要耗時1秒,例如hello…將會需要等待3秒。

發送端:

newtask.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.io.ioexception;
import com.rabbitmq.client.channel;
import com.rabbitmq.client.connection;
import com.rabbitmq.client.connectionfactory;
public class newtask
{
    //隊列名稱
    private final static string queue_name = "workqueue";
    public static void main(string[] args) throws ioexception
     {
        //創建連接和頻道
        connectionfactory factory = new connectionfactory();
        factory.sethost("localhost");
        connection connection = factory.newconnection();
        channel channel = connection.createchannel();
        //聲明隊列
        channel.queuedeclare(queue_name, false, false, false, null);
        //發送10條消息,依次在消息后面附加1-10個點
        for (int i = 0; i < 10; i++)
          {
            string dots = "";
            for (int j = 0; j <= i; j++)
               {
                dots += ".";
            }
            string message = "helloworld" + dots+dots.length();
            channel.basicpublish("", queue_name, null, message.getbytes());
            system.out.println(" [x] sent '" + message + "'");
        }
        //關閉頻道和資源
        channel.close();
        connection.close();
    }
}

接收端:

work.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import com.rabbitmq.client.channel;
import com.rabbitmq.client.connection;
import com.rabbitmq.client.connectionfactory;
import com.rabbitmq.client.queueingconsumer;
public class work
{
    //隊列名稱
    private final static string queue_name = "workqueue";
    public static void main(string[] argv) throws java.io.ioexception,
       java.lang.interruptedexception
     {
        //區分不同工作進程的輸出
        int hashcode = work.class.hashcode();
        //創建連接和頻道
        connectionfactory factory = new connectionfactory();
        factory.sethost("localhost");
        connection connection = factory.newconnection();
        channel channel = connection.createchannel();
        //聲明隊列
        channel.queuedeclare(queue_name, false, false, false, null);
        system.out.println(hashcode
            + " [*] waiting for messages. to exit press ctrl+c");
        queueingconsumer consumer = new queueingconsumer(channel);
        // 指定消費隊列
        channel.basicconsume(queue_name, true, consumer);
        while (true)
          {
            queueingconsumer.delivery delivery = consumer.nextdelivery();
            string message = new string(delivery.getbody());
            system.out.println(hashcode + " [x] received '" + message + "'");
            dowork(message);
            system.out.println(hashcode + " [x] done");
        }
    }
    /**
  * 每個點耗時1s
  * @param task
  * @throws interruptedexception
  */
    private static void dowork(string task) throws interruptedexception
     {
        for (char ch : task.tochararray())
          {
            if (ch == '.')
                thread.sleep(1000);
        }
    }
}

round-robin 轉發

使用任務隊列的好處是能夠很容易的并行工作。如果我們積壓了很多工作,我們僅僅通過增加更多的工作者就可以解決問題,使系統的伸縮性更加容易。

下面我們先運行3個工作者(work.java)實例,然后運行newtask.java,3個工作者實例都會得到信息。但是如何分配呢?讓我們來看輸出結果:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
[x] sent 'helloworld.1'
[x] sent 'helloworld..2'
[x] sent 'helloworld...3'
[x] sent 'helloworld....4'
[x] sent 'helloworld.....5'
[x] sent 'helloworld......6'
[x] sent 'helloworld.......7'
[x] sent 'helloworld........8'
[x] sent 'helloworld.........9'
[x] sent 'helloworld..........10'
工作者1
605645 [*] waiting for messages. to exit press ctrl+c
605645 [x] received 'helloworld.1'
605645 [x] done
605645 [x] received 'helloworld....4'
605645 [x] done
605645 [x] received 'helloworld.......7'
605645 [x] done
605645 [x] received 'helloworld..........10'
605645 [x] done
 
工作者2
18019860 [*] waiting for messages. to exit press ctrl+c
18019860 [x] received 'helloworld..2'
18019860 [x] done
18019860 [x] received 'helloworld.....5'
18019860 [x] done
18019860 [x] received 'helloworld........8'
18019860 [x] done
 
工作者3
18019860 [*] waiting for messages. to exit press ctrl+c
18019860 [x] received 'helloworld...3'
18019860 [x] done
18019860 [x] received 'helloworld......6'
18019860 [x] done
18019860 [x] received 'helloworld.........9'
18019860 [x] done

可以看到,默認的,rabbitmq會一個一個的發送信息給下一個消費者(consumer),而不考慮每個任務的時長等等,且是一次性分配,并非一個一個分配。平均的每個消費者將會獲得相等數量的消息。這樣分發消息的方式叫做round-robin。

2、消息應答(messageacknowledgments)

執行一個任務需要花費幾秒鐘。你可能會擔心當一個工作者在執行任務時發生中斷。我們上面的代碼,一旦rabbitmq交付了一個信息給消費者,會馬上從內存中移除這個信息。在這種情況下,如果殺死正在執行任務的某個工作者,我們會丟失它正在處理的信息。我們也會丟失已經轉發給這個工作者且它還未執行的消息。

上面的例子,我們首先開啟兩個任務,然后執行發送任務的代碼(newtask.java),然后立即關閉第二個任務,結果為:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
工作者2
31054905[*]waitingformessages.toexitpressctrl+c
31054905[x]received'helloworld..2'
31054905[x]done
31054905[x]received'helloworld....4'
工作者1
18019860[*]waitingformessages.toexitpressctrl+c
18019860[x]received'helloworld.1'
18019860[x]done
18019860[x]received'helloworld...3'
18019860[x]done
18019860[x]received'helloworld.....5'
18019860[x]done
18019860[x]received'helloworld.......7'
18019860[x]done
18019860[x]received'helloworld.........9'
18019860[x]done

可以看到,第二個工作者至少丟失了6,8,10號任務,且4號任務未完成。

但是,我們不希望丟失任何任務(信息)。當某個工作者(接收者)被殺死時,我們希望將任務傳遞給另一個工作者。

為了保證消息永遠不會丟失,rabbitmq支持消息應答(messageacknowledgments)。消費者發送應答給rabbitmq,告訴它信息已經被接收和處理,然后rabbitmq可以自由的進行信息刪除。

如果消費者被殺死而沒有發送應答,rabbitmq會認為該信息沒有被完全的處理,然后將會重新轉發給別的消費者。通過這種方式,你可以確認信息不會被丟失,即使消者偶爾被殺死。

這種機制并沒有超時時間這么一說,rabbitmq只有在消費者連接斷開是重新轉發此信息。如果消費者處理一個信息需要耗費特別特別長的時間是允許的。

消息應答默認是打開的。上面的代碼中我們通過顯示的設置autoask=true關閉了這種機制。下面我們修改代碼(work.java):

?
1
2
3
4
boolean ack = false ; //打開應答機制
channel.basicconsume(queue_name, ack, consumer);
//另外需要在每次處理完成一個消息后,手動發送一次應答。
channel.basicack(delivery.getenvelope().getdeliverytag(), false);

完整修改后的work.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import com.rabbitmq.client.channel;
import com.rabbitmq.client.connection;
import com.rabbitmq.client.connectionfactory;
import com.rabbitmq.client.queueingconsumer;
public class work
{
    //隊列名稱
    private final static string queue_name = "workqueue";
    public static void main(string[] argv) throws java.io.ioexception,
       java.lang.interruptedexception
     {
        //區分不同工作進程的輸出
        int hashcode = work.class.hashcode();
        //創建連接和頻道
        connectionfactory factory = new connectionfactory();
        factory.sethost("localhost");
        connection connection = factory.newconnection();
        channel channel = connection.createchannel();
        //聲明隊列
        channel.queuedeclare(queue_name, false, false, false, null);
        system.out.println(hashcode
            + " [*] waiting for messages. to exit press ctrl+c");
        queueingconsumer consumer = new queueingconsumer(channel);
        // 指定消費隊列
        boolean ack = false ;
        //打開應答機制
        channel.basicconsume(queue_name, ack, consumer);
        while (true)
          {
            queueingconsumer.delivery delivery = consumer.nextdelivery();
            string message = new string(delivery.getbody());
            system.out.println(hashcode + " [x] received '" + message + "'");
            dowork(message);
            system.out.println(hashcode + " [x] done");
            //發送應答
            channel.basicack(delivery.getenvelope().getdeliverytag(), false);
        }
    }
}

測試:

我們把消息數量改為5,然后先打開兩個消費者(work.java),然后發送任務(newtask.java),立即關閉一個消費者,觀察輸出:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[x]sent'helloworld.1'
[x]sent'helloworld..2'
[x]sent'helloworld...3'
[x]sent'helloworld....4'
[x]sent'helloworld.....5'
工作者2
18019860[*]waitingformessages.toexitpressctrl+c
18019860[x]received'helloworld..2'
18019860[x]done
18019860[x]received'helloworld....4'
工作者1
31054905[*]waitingformessages.toexitpressctrl+c
31054905[x]received'helloworld.1'
31054905[x]done
31054905[x]received'helloworld...3'
31054905[x]done
31054905[x]received'helloworld.....5'
31054905[x]done
31054905[x]received'helloworld....4'
31054905[x]done

可以看到工作者2沒有完成的任務4,重新轉發給工作者1進行完成了。

3、消息持久化(messagedurability)

我們已經學習了即使消費者被殺死,消息也不會被丟失。但是如果此時rabbitmq服務被停止,我們的消息仍然會丟失。

當rabbitmq退出或者異常退出,將會丟失所有的隊列和信息,除非你告訴它不要丟失。我們需要做兩件事來確保信息不會被丟失:我們需要給所有的隊列和消息設置持久化的標志。

第一,我們需要確認rabbitmq永遠不會丟失我們的隊列。為了這樣,我們需要聲明它為持久化的。

booleandurable=true;

channel.queuedeclare("task_queue",durable,false,false,null);

注:rabbitmq不允許使用不同的參數重新定義一個隊列,所以已經存在的隊列,我們無法修改其屬性。

第二,我們需要標識我們的信息為持久化的。通過設置messageproperties(implementsbasicproperties)值為persistent_text_plain。

channel.basicpublish("","task_queue",messageproperties.persistent_text_plain,message.getbytes());

現在你可以執行一個發送消息的程序,然后關閉服務,再重新啟動服務,運行消費者程序做下實驗。

4、公平轉發(fairdispatch)

或許會發現,目前的消息轉發機制(round-robin)并非是我們想要的。例如,這樣一種情況,對于兩個消費者,有一系列的任務,奇數任務特別耗時,而偶數任務卻很輕松,這樣造成一個消費者一直繁忙,另一個消費者卻很快執行完任務后等待。

造成這樣的原因是因為rabbitmq僅僅是當消息到達隊列進行轉發消息。并不在乎有多少任務消費者并未傳遞一個應答給rabbitmq。僅僅盲目轉發所有的奇數給一個消費者,偶數給另一個消費者。

為了解決這樣的問題,我們可以使用basicqos方法,傳遞參數為prefetchcount=1。這樣告訴rabbitmq不要在同一時間給一個消費者超過一條消息。換句話說,只有在消費者空閑的時候會發送下一條信息。

?
1
2
int prefetchcount = 1;
channel.basicqos(prefetchcount);

Java工作隊列代碼詳解

注:如果所有的工作者都處于繁忙狀態,你的隊列有可能被填充滿。你可能會觀察隊列的使用情況,然后增加工作者,或者使用別的什么策略。

測試:改變發送消息的代碼,將消息末尾點數改為6-2個,然后首先開啟兩個工作者,接著發送消息:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[x] sent 'helloworld......6'
[x] sent 'helloworld.....5'
[x] sent 'helloworld....4'
[x] sent 'helloworld...3'
[x] sent 'helloworld..2'
工作者1
18019860 [*] waiting for messages. to exit press ctrl+c
18019860 [x] received 'helloworld......6'
18019860 [x] done
18019860 [x] received 'helloworld...3'
18019860 [x] done
工作者2
31054905 [*] waiting for messages. to exit press ctrl+c
31054905 [x] received 'helloworld.....5'
31054905 [x] done
31054905 [x] received 'helloworld....4'
31054905 [x] done
31054905 [x] received 'helloworld..2'
31054905 [x] done

可以看出此時并沒有按照之前的round-robin機制進行轉發消息,而是當消費者不忙時進行轉發。且這種模式下支持動態增加消費者,因為消息并沒有發送出去,動態增加了消費者馬上投入工作。而默認的轉發機制會造成,即使動態增加了消費者,此時的消息已經分配完畢,無法立即加入工作,即使有很多未完成的任務。

5、完整的代碼

newtask.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.io.ioexception;
import com.rabbitmq.client.channel;
import com.rabbitmq.client.connection;
import com.rabbitmq.client.connectionfactory;
import com.rabbitmq.client.messageproperties;
public class newtask
{
    // 隊列名稱
    private final static string queue_name = "workqueue_persistence";
    public static void main(string[] args) throws ioexception
     {
        // 創建連接和頻道
        connectionfactory factory = new connectionfactory();
        factory.sethost("localhost");
        connection connection = factory.newconnection();
        channel channel = connection.createchannel();
        // 聲明隊列
        boolean durable = true;
        // 1、設置隊列持久化
        channel.queuedeclare(queue_name, durable, false, false, null);
        // 發送10條消息,依次在消息后面附加1-10個點
        for (int i = 5; i > 0; i--)
          {
            string dots = "";
            for (int j = 0; j <= i; j++)
               {
                dots += ".";
            }
            string message = "helloworld" + dots + dots.length();
            // messageproperties 2、設置消息持久化
            channel.basicpublish("", queue_name,
                 messageproperties.persistent_text_plain, message.getbytes());
            system.out.println(" [x] sent '" + message + "'");
        }
        // 關閉頻道和資源
        channel.close();
        connection.close();
    }
}

work.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import com.rabbitmq.client.channel;
import com.rabbitmq.client.connection;
import com.rabbitmq.client.connectionfactory;
import com.rabbitmq.client.queueingconsumer;
public class work
{
    // 隊列名稱
    private final static string queue_name = "workqueue_persistence";
    public static void main(string[] argv) throws java.io.ioexception,
       java.lang.interruptedexception
     {
        // 區分不同工作進程的輸出
        int hashcode = work.class.hashcode();
        // 創建連接和頻道
        connectionfactory factory = new connectionfactory();
        factory.sethost("localhost");
        connection connection = factory.newconnection();
        channel channel = connection.createchannel();
        // 聲明隊列
        boolean durable = true;
        channel.queuedeclare(queue_name, durable, false, false, null);
        system.out.println(hashcode
            + " [*] waiting for messages. to exit press ctrl+c");
        //設置最大服務轉發消息數量
        int prefetchcount = 1;
        channel.basicqos(prefetchcount);
        queueingconsumer consumer = new queueingconsumer(channel);
        // 指定消費隊列
        boolean ack = false;
        // 打開應答機制
        channel.basicconsume(queue_name, ack, consumer);
        while (true)
          {
            queueingconsumer.delivery delivery = consumer.nextdelivery();
            string message = new string(delivery.getbody());
            system.out.println(hashcode + " [x] received '" + message + "'");
            dowork(message);
            system.out.println(hashcode + " [x] done");
            //channel.basicack(delivery.getenvelope().getdeliverytag(), false);
            channel.basicack(delivery.getenvelope().getdeliverytag(), false);
        }
    }
    /**
  * 每個點耗時1s
  *
  * @param task
  * @throws interruptedexception
  */
    private static void dowork(string task) throws interruptedexception
     {
        for (char ch : task.tochararray())
          {
            if (ch == '.')
                thread.sleep(1000);
        }
    }
}

總結

以上就是本文關于java工作隊列代碼詳解的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!

原文鏈接:https://www.2cto.com/kf/201608/541697.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 欧美在线亚洲 | 久久久久久国产精品美女 | 天天摸天天摸 | 国产真实精品久久二三区 | 国产精品极品美女在线观看免费 | 精久久久 | 天堂中文 | 91亚洲日本aⅴ精品一区二区 | 亚洲免费a| 久久综合一区二区三区 | 国产视频www | 久久福利电影 | 中文字幕亚洲综合久久久软件 | 欧美成人h版在线观看 | 久久精品一区二区三区四区 | 视频一区二区中文字幕 | 激情久久久久 | 精品久久一区二区 | 日本一区二区三区中文字幕 | 日韩免费在线观看视频 | 国产在线视频a | 久久亚洲国产精品 | 国产精品久久久久久亚洲调教 | 国产精品久久久久久久久久久免费看 | 91精品视频在线播放 | 精品在线一区二区 | 在线免费观看黄色 | 亚洲激情久久 | 久久亚| 一区二区三区成人久久爱 | 日韩激情 | 精品日韩一区二区三区 | 伊人中文 | a毛片视频 | 国产精品欧美一区二区三区 | 国产中文字幕在线看 | 久久中文字幕视频 | 日本国产欧美 | 男人天堂av网 | 中文字幕视频免费 | 日韩国产欧美视频 |