示例将演示如何使用软件包 SDK 创建事件驱动触发器 (SimpleMessageListenerContainer)

事件驱动触发器 - 推送机制

触发器等待事件发生,例如,消息监听器开始监听。

  • 事件详情存储在内存中,消息监听器等待消息。
  • 当事件发生时,它将运行 consumer.accept(<RecordValue Instance>) 方法并触发关联机器人。

以下示例展示了如何创建简单的 ActiveMQ 消息侦听器 (SimpleMessageListenerContainer) 来演示触发器推送机制。

@BotCommand(commandType = BotCommand.CommandType.Trigger) @CommandPkg(label = "JMS Trigger"、description = "JMS Trigger"、icon = "jms.svg"、name = "jmsTrigger"、return_type = RECORD、return_name = "TriggerData"、return_description = "Available keys: triggerType") public class JMSQueue implements SessionAwareMessageListener { // Map storing multiple MessageListenerContainer private static final Map<String, MessageListenerContainer> taskMap = new ConcurrentHashMap<>(); @TriggerId private String triggerUid; @TriggerConsumer private Consumer consumer; //This method is called by MessageListenerContainer when a message arrives. // At this point、the trigger get enabled @Override public void onMessage(javax.jms.Message message、Session session) throws JMSException { consumer.accept(getRecordValue()); } private RecordValue getRecordValue() { List<Schema> schemas = new LinkedList<>(); List<Value> values = new LinkedList<>(); schemas.add(new Schema("triggerType")); values.add(new StringValue("JMSQueue")); RecordValue recordValue = new RecordValue(); recordValue.set(new Record(schemas、values)); return recordValue; } /* * Starts the trigger. * * Use this method to setup the trigger、such as、setup the MessageListenerContainer and start it. */ @StartListen public void startTrigger(@Idx(index = "1"、type = AttributeType.TEXT) @Pkg(label = "Provide the broker URL") @NotEmpty String brokerURL、@Idx(index = "2"、type = AttributeType.TEXT) @Pkg(label = "Provide the queue name") @NotEmpty String queueName) { if (taskMap.get(triggerUid) == null) { synchronized (this) { if (taskMap.get(triggerUid) == null) { SimpleMessageListenerContainer messageListenerContainer = new SimpleMessageListenerContainer(); messageListenerContainer.setConnectionFactory(new PooledConnectionFactory(brokerURL)); messageListenerContainer.setDestinationName(queueName); messageListenerContainer.setMessageListener(this); messageListenerContainer.start(); taskMap.put(triggerUid、messageListenerContainer); } } } } /* * Cancel all the tasks and clear the map. */ @StopAllTriggers public void stopAllTriggers() { taskMap.forEach((k、v) -> { v.stop(); taskMap.remove(k); }); } /* * Cancel the tasks and remove from the map * * @param triggerUid */ @StopListen public void stopListen(String triggerUid) { taskMap.get(triggerUid).stop(); taskMap.remove(triggerUid); } public String getTriggerUid() { return triggerUid; } public void setTriggerUid(String triggerUid) { this.triggerUid = triggerUid; } public Consumer getConsumer() { return consumer; } public void setConsumer(Consumer consumer) { this.consumer = consumer; } }