Java için ApsaraMQ for RocketMQ TCP istemci SDK'sını kullanarak mesajlara abone olun. Bu konuda abonelik modları, teslimat modları ve eksiksiz kod örnekleri ele alınmaktadır.
Abonelik modları
ApsaraMQ for RocketMQ kümeleme ve yayınlama olmak üzere iki abonelik modunu destekler.
Kümeleme (varsayılan)
Kümeleme modunda aynı tüketici grubundaki tüm tüketiciler mesaj yükünü eşit olarak paylaşır. Her mesaj yalnızca bir tüketiciye iletilir.
Örneğin bir konu 9 mesaj içeriyorsa ve tüketici grubunda 3 tüketici varsa her tüketici 3 mesaj alır.
// Clustering is the default mode. To set it explicitly:
properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);
Yayınlama
Yayınlama modunda gruptaki her tüketici her mesajın tam bir kopyasını alır.
Örneğin bir konu 9 mesaj içeriyorsa ve tüketici grubunda 3 tüketici varsa her tüketici 9 mesajın tamamını alır.
// Set the subscription mode to broadcasting.
properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.BROADCASTING);
Aynı grup kimliğindeki tüm tüketici örnekleri tutarlı abonelikler kullanmalıdır.
Yayınlama modu sıralı mesaj göndermeyi veya almayı, tüketim ilerlemesinin izlenmesini ya da tüketici ofsetlerinin sıfırlanmasını desteklemez. Daha fazla bilgi için bkz. Kümeleme tüketimi ve yayınlama tüketimi.
Teslimat modları
ApsaraMQ for RocketMQ gönderme (push) ve çekme (pull) olmak üzere iki teslimat modunu destekler.
| Mod | Açıklama | En uygun olduğu durumlar |
|---|---|---|
| Gönderme (Push) | Mesajlar ApsaraMQ for RocketMQ'dan tüketicilere gönderilir. Ayrıca toplu iş tüketimini destekler. | Çoğu kullanım senaryosu |
| Çekme (Pull) | Tüketiciler mesajları ApsaraMQ for RocketMQ'dan çeker; bu sayede mesaj alma konusunda daha fazla seçenek ve mesaj çekmede daha fazla esneklik sunar. | Mesaj getirme üzerinde hassas kontrol gerektiren kullanım senaryoları |
Çekme tüketicileri için Enterprise Platinum Edition örneği gerekir.
Çekme tüketicileri yalnızca Virtual Private Cloud (VPC) üzerinden bağlanabilir.
Çekme tüketicisi yöntemlerinin ve parametrelerinin tam listesi için bkz. Yöntemler ve parametreler.
Örnek kod
Aşağıdaki örnekler gönderme (push), toplu iş gönderme ve çekme (pull) tüketimini gösterir. Daha fazla örnek için GitHub'daki ApsaraMQ for RocketMQ kod deposuna bakın.
Aşağıdaki yer tutucuları gerçek değerlerinizle değiştirin:
| Yer Tutucu | Açıklama | Nerede bulunur |
|---|---|---|
<your-group-id> |
Tüketici grubu kimliği | ApsaraMQ for RocketMQ konsolu |
<your-tcp-endpoint> |
TCP uç noktası | Konsoldaki Instance Details sayfasının TCP Endpoint bölümü |
Tüm örnekler AccessKey kimlik bilgilerini ALIBABA_CLOUD_ACCESS_KEY_ID ve ALIBABA_CLOUD_ACCESS_KEY_SECRET ortam değişkenlerinden okur.
Gönderme (Push) tüketicisi
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import java.util.Properties;
public class ConsumerTest {
public static void main(String[] args) {
Properties properties = new Properties();
// The consumer group ID created in the ApsaraMQ for RocketMQ console.
properties.put(PropertyKeyConst.GROUP_ID, "<your-group-id>");
// Read AccessKey credentials from environment variables.
properties.put(PropertyKeyConst.AccessKey, System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
properties.put(PropertyKeyConst.SecretKey, System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// The TCP endpoint from the Instance Details page in the console.
properties.put(PropertyKeyConst.NAMESRV_ADDR, "<your-tcp-endpoint>");
// Clustering mode (default). Uncomment the line below to switch to broadcasting.
// properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);
// properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.BROADCASTING);
Consumer consumer = ONSFactory.createConsumer(properties);
// Subscribe to specific tags. Use "||" as a separator.
consumer.subscribe("TopicTestMQ", "TagA||TagB", new MessageListener() {
public Action consume(Message message, ConsumeContext context) {
System.out.println("Receive: " + message);
return Action.CommitMessage;
}
});
// Subscribe to another topic with all tags.
// To unsubscribe, remove the subscription code and restart the consumer.
consumer.subscribe("TopicTestMQ-Other", "*", new MessageListener() {
public Action consume(Message message, ConsumeContext context) {
System.out.println("Receive: " + message);
return Action.CommitMessage;
}
});
consumer.start();
System.out.println("Consumer Started");
}
}
Gönderme (Push) tüketicisi (toplu iş tüketimi)
Toplu iş tüketimi Java için TCP istemci SDK'sının 1.8.7.3 veya sonraki bir sürümünü gerektirir. Sürüm ayrıntıları için bkz. Sürüm notları.
Toplu iş davranışını iki özellik kontrol eder:
| Özellik | Açıklama | Geçerli değerler | Varsayılan |
|---|---|---|---|
ConsumeMessageBatchMaxSize |
Toplu iş başına maksimum mesaj sayısı. Önbelleğe alınan sayı bu değere ulaştığında SDK geri aramayı çağırır. | 1 ila 1024 | 32 |
BatchConsumeMaxAwaitDurationInSeconds |
Kısmi bir toplu işi teslim etmeden önceki maksimum bekleme süresi (saniye). Toplu iş boyutundan bağımsız olarak bu süre dolduğunda SDK geri aramayı çağırır. | 0 ila 450 | 0 |
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.batch.BatchConsumer;
import com.aliyun.openservices.ons.api.batch.BatchMessageListener;
import java.util.List;
import java.util.Properties;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.tcp.example.MqConfig;
public class SimpleBatchConsumer {
public static void main(String[] args) {
Properties consumerProperties = new Properties();
// The consumer group ID created in the ApsaraMQ for RocketMQ console.
consumerProperties.setProperty(PropertyKeyConst.GROUP_ID, MqConfig.GROUP_ID);
// Read AccessKey credentials from environment variables.
consumerProperties.put(PropertyKeyConst.AccessKey, System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
consumerProperties.put(PropertyKeyConst.SecretKey, System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// The TCP endpoint from the Instance Details page in the console.
consumerProperties.setProperty(PropertyKeyConst.NAMESRV_ADDR, MqConfig.NAMESRV_ADDR);
// Set the maximum batch size to 128 messages.
consumerProperties.setProperty(PropertyKeyConst.ConsumeMessageBatchMaxSize, String.valueOf(128));
// Set the maximum wait time between batches to 10 seconds.
consumerProperties.setProperty(PropertyKeyConst.BatchConsumeMaxAwaitDurationInSeconds, String.valueOf(10));
BatchConsumer batchConsumer = ONSFactory.createBatchConsumer(consumerProperties);
batchConsumer.subscribe(MqConfig.TOPIC, MqConfig.TAG, new BatchMessageListener() {
@Override
public Action consume(final List<Message> messages, ConsumeContext context) {
System.out.printf("Batch-size: %d\n", messages.size());
// Process messages in batches.
return Action.CommitMessage;
}
});
// Start the batch consumer.
batchConsumer.start();
System.out.println("Consumer start success.");
// Keep the process alive to continue consuming.
try {
Thread.sleep(200000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Çekme (Pull) tüketicisi
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.PullConsumer;
import com.aliyun.openservices.ons.api.TopicPartition;
import java.util.List;
import java.util.Properties;
import java.util.Set;
public class PullConsumerClient {
public static void main(String[] args){
Properties properties = new Properties();
// The consumer group ID created in the ApsaraMQ for RocketMQ console.
properties.setProperty(PropertyKeyConst.GROUP_ID, "<your-group-id>");
// Read AccessKey credentials from environment variables.
properties.put(PropertyKeyConst.AccessKey, System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
properties.put(PropertyKeyConst.SecretKey, System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// The TCP endpoint from the Instance Details page in the console.
properties.put(PropertyKeyConst.NAMESRV_ADDR, "<your-tcp-endpoint>");
PullConsumer consumer = ONSFactory.createPullConsumer(properties);
// Start the pull consumer.
consumer.start();
// Get all partitions for the topic.
Set<TopicPartition> topicPartitions = consumer.topicPartitions("topic-xxx");
// Assign partitions to this consumer.
consumer.assign(topicPartitions);
while (true) {
// Poll for messages with a 3-second timeout.
List<Message> messages = consumer.poll(3000);
System.out.printf("Received message: %s %n", messages);
}
}
}
Bölümler ve ofsetler hakkında daha fazla bilgi için bkz. Terimler.
Mesaj yeniden denemesi
Mesaj tüketimi başarısız olursa veya zaman aşımına uğrarsa ApsaraMQ for RocketMQ mesajı otomatik olarak yeniden iletir. Daha fazla bilgi için bkz. Mesaj yeniden denemesi.