17年底我最后工作的一个内容(坑)是需要用到Streaming API,没想到从此对我影响如此深远...
当时是需要监听case两个字段任意一个的变化,前台抓到这个变化之后,传到后台生成一个SessionTime的Object.
做这个需求,首先需要在系统插入一个pushTopic对象,注册一个监听事件。
3.
1.后台运行:
PushTopic pushTopic = new PushTopic();
pushTopic.Name = 'XXXXXX';
pushTopic.Query = 'SELECT Id,XXX,XXX FROM Case WHERE XXX';
pushTopic.ApiVersion = 37.0;
pushTopic.NotifyForOperationCreate = false;
pushTopic.NotifyForOperationUpdate = true;
pushTopic.NotifyForOperationUndelete = false;
pushTopic.NotifyForOperationDelete = false;
pushTopic.NotifyForFields = 'Referenced';
insert pushTopic;
2.static resource:
Cometd.jsjquery_cometd.js
json2.js
jquery-1.5.1.js
3.前台页面写入:
$.cometd.init({
url: window.location.protocol+'//'+window.location.hostname+'/cometd/36.0/',
requestHeaders: { Authorization: 'OAuth {!$Api.Session_ID}'}
});
// Subscribe to a topic. JSON-encoded update will be returned
// in the callback
$.cometd.subscribe('/topic/CaseStatusAndOwnerUpdates', function(message) {
debugger;
}
console.log(message);
});
到这里基本上已经实现了,但是这个也有限制需要注意。
主要是由于API版本的原因:
在36.0以及之前的版本中,在一次请求中生成多次notification(比如多次改变case的某个值),那么只有最后一次的notification会被发出去
37.0之后的版本,没有notification会被抑制,因为他们都带了一个ID。
In API version 36.0 and earlier, if multiple PushTopic notifications are generated for the same record within a short time (one millisecond) and in the same transaction, only the last notification is sent. The reason for the suppression of other notifications is because notifications are tracked at the millisecond level. If multiple notifications happen within a transaction at the same time (less than one millisecond), only the last notification can be delivered.
For example, suppose a PushTopic is set up for insertions and updates of contact records, and the PushTopic query selects fieldA. If a contact is inserted and then an Apex trigger or a workflow updates fieldA within a short time, only the notification for the update is sent. No notification is sent for the contact creation.
However, if the elapsed time between the notifications is over one millisecond, all the notifications are sent for the same record and no notification is suppressed.
API Version 37.0 and Later
In API version 37.0 and later, notifications are tracked by a unique ID and don’t depend on the time when they were generated. All notifications for the same record within one transaction are sent and no notification is suppressed.
但是这个API版本具体是因为哪里产生的差异还不确定,初步认为是导入系统的static resource决定的,然后那段匿名pushtopic,和前台代码也是一样要遵循版本写。
具体参考:
https://help.salesforce.com/articleView?id=Multiple-Streaming-API-Notifications-for-the-Same-Record-Notifications-Are-Sent-for-Untracked-Fields&language=en_US&type=1
https://help.salesforce.com/articleView?id=Only-Last-Push-Topic-Notification-is-sent-out-of-multiple-notifications-done-in-short-time&language=en_US&type=1
https://developer.salesforce.com/docs/atlas.en-us.api_streaming.meta/api_streaming/limits.htm