This is an automated email from the ASF dual-hosted git repository.

jinrongtong pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-clients.git


The following commit(s) were added to refs/heads/master by this push:
     new 1f093754 feat(csharp): parallel FIFO consume by message group (#1218)
1f093754 is described below

commit 1f093754cc65146669dbad2cb9a18bdcb3064c4c
Author: guyinyou <[email protected]>
AuthorDate: Fri Apr 10 16:53:56 2026 +0800

    feat(csharp): parallel FIFO consume by message group (#1218)
    
    - Group each receive batch by MessageView.MessageGroup when accelerator is 
on
    - Run one serial ConsumeIteratively chain per group; multiple groups in 
parallel
    - Default off; enable via 
PushConsumer.Builder.SetEnableFifoConsumeAccelerator
    - Add FifoConsumeService.GroupFifoBatchByMessageGroup unit tests
    
    Co-authored-by: guyinyou <[email protected]>
---
 .../rocketmq-client-csharp/FifoConsumeService.cs   | 66 ++++++++++++++-
 csharp/rocketmq-client-csharp/PushConsumer.cs      | 25 +++++-
 csharp/tests/FifoConsumeServiceTest.cs             | 97 ++++++++++++++++++++++
 3 files changed, 181 insertions(+), 7 deletions(-)

diff --git a/csharp/rocketmq-client-csharp/FifoConsumeService.cs 
b/csharp/rocketmq-client-csharp/FifoConsumeService.cs
index b293c41d..19989234 100644
--- a/csharp/rocketmq-client-csharp/FifoConsumeService.cs
+++ b/csharp/rocketmq-client-csharp/FifoConsumeService.cs
@@ -15,6 +15,7 @@
  * limitations under the License.
  */
 
+using System;
 using System.Collections.Generic;
 using System.Threading;
 using System.Threading.Tasks;
@@ -26,15 +27,74 @@ namespace Org.Apache.Rocketmq
     {
         private static readonly ILogger Logger = 
MqLogManager.CreateLogger<FifoConsumeService>();
 
+        private readonly bool _enableFifoConsumeAccelerator;
+
         public FifoConsumeService(string clientId, IMessageListener 
messageListener,
-            TaskScheduler consumptionExecutor, CancellationToken 
consumptionCtsToken) :
+            TaskScheduler consumptionExecutor, CancellationToken 
consumptionCtsToken,
+            bool enableFifoConsumeAccelerator = false) :
             base(clientId, messageListener, consumptionExecutor, 
consumptionCtsToken)
         {
+            _enableFifoConsumeAccelerator = enableFifoConsumeAccelerator;
+        }
+
+        /// <summary>
+        /// Groups FIFO batch by <see cref="MessageView.MessageGroup"/> 
(aligned with golang fifoConsumeService / groupMessageBy).
+        /// Messages with null or empty group go to <paramref 
name="withoutGroup"/> and share one serial chain.
+        /// </summary>
+        internal static void 
GroupFifoBatchByMessageGroup(IReadOnlyList<MessageView> messageViews,
+            out Dictionary<string, List<MessageView>> byGroup, out 
List<MessageView> withoutGroup)
+        {
+            byGroup = new Dictionary<string, List<MessageView>>();
+            withoutGroup = new List<MessageView>();
+            foreach (var mv in messageViews)
+            {
+                var g = mv.MessageGroup;
+                if (string.IsNullOrEmpty(g))
+                {
+                    withoutGroup.Add(mv);
+                }
+                else if (!byGroup.TryGetValue(g, out var list))
+                {
+                    list = new List<MessageView>();
+                    byGroup[g] = list;
+                    list.Add(mv);
+                }
+                else
+                {
+                    list.Add(mv);
+                }
+            }
         }
 
         public override void Consume(ProcessQueue pq, List<MessageView> 
messageViews)
         {
-            ConsumeIteratively(pq, messageViews.GetEnumerator());
+            if (!_enableFifoConsumeAccelerator || messageViews.Count <= 1)
+            {
+                ConsumeIteratively(pq, messageViews.GetEnumerator());
+                return;
+            }
+
+            GroupFifoBatchByMessageGroup(messageViews, out var byGroup, out 
var withoutGroup);
+
+            var groupNum = byGroup.Count;
+            if (withoutGroup.Count > 0)
+            {
+                groupNum++;
+            }
+
+            Logger.LogDebug(
+                "FifoConsumeService parallel consume, messageViewsNum={Count}, 
groupNum={GroupNum}, clientId={ClientId}",
+                messageViews.Count, groupNum, ClientId);
+
+            foreach (var group in byGroup.Values)
+            {
+                ConsumeIteratively(pq, group.GetEnumerator());
+            }
+
+            if (withoutGroup.Count > 0)
+            {
+                ConsumeIteratively(pq, withoutGroup.GetEnumerator());
+            }
         }
 
         public void ConsumeIteratively(ProcessQueue pq, 
IEnumerator<MessageView> iterator)
@@ -65,4 +125,4 @@ namespace Org.Apache.Rocketmq
                 TaskContinuationOptions.ExecuteSynchronously);
         }
     }
-}
\ No newline at end of file
+}
diff --git a/csharp/rocketmq-client-csharp/PushConsumer.cs 
b/csharp/rocketmq-client-csharp/PushConsumer.cs
index 5d246079..c0cd1dbb 100644
--- a/csharp/rocketmq-client-csharp/PushConsumer.cs
+++ b/csharp/rocketmq-client-csharp/PushConsumer.cs
@@ -47,6 +47,7 @@ namespace Org.Apache.Rocketmq
         private readonly IMessageListener _messageListener;
         private readonly int _maxCacheMessageCount;
         private readonly int _maxCacheMessageSizeInBytes;
+        private readonly bool _enableFifoConsumeAccelerator;
 
         private readonly ConcurrentDictionary<MessageQueue, ProcessQueue> 
_processQueueTable;
         private ConsumeService _consumeService;
@@ -73,7 +74,8 @@ namespace Org.Apache.Rocketmq
         /// </summary>
         public PushConsumer(ClientConfig clientConfig, string consumerGroup,
             ConcurrentDictionary<string, FilterExpression> 
subscriptionExpressions, IMessageListener messageListener,
-            int maxCacheMessageCount, int maxCacheMessageSizeInBytes, int 
consumptionThreadCount)
+            int maxCacheMessageCount, int maxCacheMessageSizeInBytes, int 
consumptionThreadCount,
+            bool enableFifoConsumeAccelerator = false)
             : base(clientConfig, consumerGroup)
         {
             _clientConfig = clientConfig;
@@ -85,6 +87,7 @@ namespace Org.Apache.Rocketmq
             _messageListener = messageListener;
             _maxCacheMessageCount = maxCacheMessageCount;
             _maxCacheMessageSizeInBytes = maxCacheMessageSizeInBytes;
+            _enableFifoConsumeAccelerator = enableFifoConsumeAccelerator;
 
             _scanAssignmentCts = new CancellationTokenSource();
 
@@ -238,8 +241,10 @@ namespace Org.Apache.Rocketmq
             if (_pushSubscriptionSettings.IsFifo())
             {
                 Logger.LogInformation(
-                    $"Create FIFO consume service, 
consumerGroup={_consumerGroup}, clientId={ClientId}");
-                return new FifoConsumeService(ClientId, _messageListener, 
_consumptionTaskScheduler, _consumptionCts.Token);
+                    "Create FIFO consume service, 
consumerGroup={ConsumerGroup}, clientId={ClientId}, 
enableFifoConsumeAccelerator={Accelerator}",
+                    _consumerGroup, ClientId, _enableFifoConsumeAccelerator);
+                return new FifoConsumeService(ClientId, _messageListener, 
_consumptionTaskScheduler, _consumptionCts.Token,
+                    _enableFifoConsumeAccelerator);
             }
             Logger.LogInformation(
                 $"Create standard consume service, 
consumerGroup={_consumerGroup}, clientId={ClientId}");
@@ -706,6 +711,7 @@ namespace Org.Apache.Rocketmq
             private int _maxCacheMessageCount = 1024;
             private int _maxCacheMessageSizeInBytes = 64 * 1024 * 1024;
             private int _consumptionThreadCount = 20;
+            private bool _enableFifoConsumeAccelerator;
 
             public Builder SetClientConfig(ClientConfig clientConfig)
             {
@@ -765,6 +771,17 @@ namespace Org.Apache.Rocketmq
                 return this;
             }
 
+            /// <summary>
+            /// When the subscription is FIFO and this is true, messages in 
one receive batch are consumed in parallel
+            /// across distinct <see cref="MessageView.MessageGroup"/> values; 
order within each group stays serial
+            /// (aligned with golang WithPushEnableFifoConsumeAccelerator).
+            /// </summary>
+            public Builder SetEnableFifoConsumeAccelerator(bool 
enableFifoConsumeAccelerator)
+            {
+                _enableFifoConsumeAccelerator = enableFifoConsumeAccelerator;
+                return this;
+            }
+
             public async Task<PushConsumer> Build()
             {
                 Preconditions.CheckArgument(null != _clientConfig, 
"clientConfig has not been set yet");
@@ -774,7 +791,7 @@ namespace Org.Apache.Rocketmq
                 Preconditions.CheckArgument(null != _messageListener, 
"messageListener has not been set yet");
                 var pushConsumer = new PushConsumer(_clientConfig, 
_consumerGroup, _subscriptionExpressions,
                     _messageListener, _maxCacheMessageCount,
-                    _maxCacheMessageSizeInBytes, _consumptionThreadCount);
+                    _maxCacheMessageSizeInBytes, _consumptionThreadCount, 
_enableFifoConsumeAccelerator);
                 await pushConsumer.Start();
                 return pushConsumer;
             }
diff --git a/csharp/tests/FifoConsumeServiceTest.cs 
b/csharp/tests/FifoConsumeServiceTest.cs
new file mode 100644
index 00000000..b2ac2eff
--- /dev/null
+++ b/csharp/tests/FifoConsumeServiceTest.cs
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System.Collections.Generic;
+using System.Text;
+using Google.Protobuf;
+using Google.Protobuf.WellKnownTypes;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Org.Apache.Rocketmq;
+using Proto = Apache.Rocketmq.V2;
+
+namespace tests
+{
+    [TestClass]
+    public class FifoConsumeServiceTest
+    {
+        private static MessageView CreateMessageView(string messageGroup, 
string messageIdSuffix = "")
+        {
+            var sp = new Proto.SystemProperties
+            {
+                MessageType = Proto.MessageType.Fifo,
+                MessageId = MessageIdGenerator.GetInstance().Next() + 
messageIdSuffix,
+                BornHost = "127.0.0.1:8080",
+                BodyDigest = new Proto.Digest { Type = Proto.DigestType.Crc32, 
Checksum = "9EF61F95" },
+                BornTimestamp = new Timestamp()
+            };
+            if (!string.IsNullOrEmpty(messageGroup))
+            {
+                sp.MessageGroup = messageGroup;
+            }
+
+            var msg = new Proto.Message
+            {
+                SystemProperties = sp,
+                Topic = new Proto.Resource { Name = "t" },
+                Body = ByteString.CopyFrom("foobar", Encoding.UTF8)
+            };
+            return MessageView.FromProtobuf(msg);
+        }
+
+        [TestMethod]
+        public void TestGroupFifoBatch_AllWithoutGroup()
+        {
+            var list = new List<MessageView>
+            {
+                CreateMessageView(null, "a"),
+                CreateMessageView(null, "b")
+            };
+            FifoConsumeService.GroupFifoBatchByMessageGroup(list, out var 
byGroup, out var withoutGroup);
+            Assert.AreEqual(0, byGroup.Count);
+            Assert.AreEqual(2, withoutGroup.Count);
+        }
+
+        [TestMethod]
+        public void TestGroupFifoBatch_SingleGroupPreservesOrder()
+        {
+            var m0 = CreateMessageView("g1", "0");
+            var m1 = CreateMessageView("g1", "1");
+            var m2 = CreateMessageView("g1", "2");
+            var list = new List<MessageView> { m0, m1, m2 };
+            FifoConsumeService.GroupFifoBatchByMessageGroup(list, out var 
byGroup, out var withoutGroup);
+            Assert.AreEqual(0, withoutGroup.Count);
+            Assert.AreEqual(1, byGroup.Count);
+            CollectionAssert.AreEqual(new[] { m0, m1, m2 }, byGroup["g1"]);
+        }
+
+        [TestMethod]
+        public void TestGroupFifoBatch_MultipleGroupsAndWithout()
+        {
+            var a = CreateMessageView("g1");
+            var b = CreateMessageView("g2");
+            var c = CreateMessageView(null);
+            var d = CreateMessageView("g1");
+            var list = new List<MessageView> { a, b, c, d };
+            FifoConsumeService.GroupFifoBatchByMessageGroup(list, out var 
byGroup, out var withoutGroup);
+            Assert.AreEqual(1, withoutGroup.Count);
+            Assert.AreSame(c, withoutGroup[0]);
+            Assert.AreEqual(2, byGroup.Count);
+            CollectionAssert.AreEqual(new[] { a, d }, byGroup["g1"]);
+            CollectionAssert.AreEqual(new[] { b }, byGroup["g2"]);
+        }
+    }
+}

Reply via email to