Our initial goal is to have a trigger fire a callout with a large amount of inserted records.
I have a trigger, which triggers a future callout from an apex class.
Trigger:
trigger pushMessageTrigger on TMP_Push_Messages__c (after insert) {
Plexure.PushMessage(Trigger.newMap.keySet());
}
Apex class:
global class Plexure {
@future(callout=true)
public static void PushMessage(Set<Id> pushMessageIds) {
List<TMP_Push_Messages__c> messages = [select consumerId__c, messageId__c from TMP_Push_Messages__c where Id IN :pushMessageIds];
for (TMP_Push_Messages__c message: messages) {
try {
// Generate guid
Blob b = Crypto.GenerateAESKey(128);
String h = EncodingUtil.ConvertTohex(b);
String guid = h.SubString(0,8)+ '-' + h.SubString(8,12) + '-' + h.SubString(12,16) + '-' + h.SubString(16,20) + '-' + h.substring(20);
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://xxxxxxxxxxxxx'+message.consumerId__c+'/xxxxxxxxxxxx');
req.setBody('{"messageId" : "'+message.messageId__c+'", "requestId" : "'+guid+'"}');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setHeader('Authorization', 'xxxxxxxx');
req.setHeader('x-vmob-authorization', 'xxxxxxxxxxx');
HTTPResponse res = http.send(req);
} catch (Exception e) {
System.debug('Got an exception');
System.debug(e);
}
}
}
I found out that it is not possible to trigger callout methods unless it has ‘@future(callout=true)’ notation and it’s not possible to pass Lists into @future methods. (Also, looked up that it’s a better practice to use ‘Trigger.newMap.keySet()’ in the trigger from this article: https://developer.salesforce.com/page/Best_Practice:_Use_future_Appropriately).
When inserting more than 100 records, an error occurs ‘Too many callouts: 101’ in the log, and I am aware that it happens because of the 100 callout limitation.
Please assist with a possible solution/workaround on how avoid hitting the limit?
Best Answer
Instead of calling a single
@future(callout=true)
method you can start a batchable running where the number of records processed in eachexecute
call can be limited to be below the governor limit:A batchable breaks work for many records up into multiple limited size lists of records. Your
TMP_Push_Messages__c
query goes into thestart
method and the rest of the code goes into theexecute
method.You also need to add the
Database.AllowsCallouts
marker interface: