Spring Cloud Alibaba AI:快速体验通义千问大模型问答
import com.aliyun.openservices.ons.api.Action;
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;
public class QuickStart {
public static void main(String[] args) {
// 假设已经有了一个有效的ONS Channel
String accessKey = "yourAccessKey";
String secretKey = "yourSecretKey";
String consumerId = "yourConsumerID";
String topic = "yourTopic";
String consumerGroup = "yourConsumerGroup";
// 初始化消费者
Properties properties = new Properties();
properties.put(PropertyKeyConst.AccessKey, accessKey);
properties.put(PropertyKeyConst.SecretKey, secretKey);
properties.put(PropertyKeyConst.ConsumerId, consumerId);
Consumer consumer = ONSFactory.createConsumer(properties);
consumer.start();
// 订阅指定Topic和Tag的消息
consumer.subscribe(topic, "*", new MessageListener() {
@Override
public Action consume(Message message, ConsumeContext context) {
System.out.println("Received message: " + new String(message.getBody()));
return Action.CommitMessage;
}
});
// 程序运行一段时间后,停止消费者
// ...
// consumer.shutdown();
}
}
这个示例展示了如何使用阿里云消息服务(ONS)的Java SDK来创建一个消费者,订阅一个特定的Topic,并处理接收到的消息。在实际应用中,你需要替换相关字段,如accessKey
、secretKey
、consumerId
、topic
和consumerGroup
,并实现消息处理逻辑。
评论已关闭