2014-02-14 110 views

回答

2

你有兩個選擇(例子中的代碼是Java):

1)使用「timer」(或石英更高級的目的)駱駝組成部分。然後,你需要一個非常簡單的定時器演員這是在每一個時期調用一個新的HTTProducer演員:

public class TimerConsumer extends UntypedConsumerActor{ 

    //Generates an event every 60 seconds: 
    @Override 
    public String getEndpointUri() { 
     return "timer://foo?fixedRate=true&period=15000"; 
    } 

    @Override 
    public void onReceive(Object m) throws Exception { 
     if (m instanceof CamelMessage){ 
      System.out.println("New Event (every 15sec)"); 
      Akka.system().actorOf(Props.create(HTTProducer.class)).tell("http://google.com", getSelf()); 
     } 
    } 
} 

2)使用Akka Scheduler

//Somewhere in the beginning of your application (Global.java for Play Framework 2) 
ActorRef httpActor = Akka.system().actorOf(Props.create(HTTProducer.class)); 
//A message every 15s to the httpActor 
Akka.system().scheduler().schedule(Duration.Zero(), 
Duration.create(15, TimeUnit.SECONDS), httpActor, "http://google.com", 
Akka.system().dispatcher(), null); 

和公共HTTProducer演員同時用於選項1)和2)如下(爲測試目的而簡化):

public class HTTProducer extends UntypedProducerActor { 

    @Override 
    public String getEndpointUri() { 
     return "http://empty.com"; 
    } 

    @Override 
    public Object onTransformOutgoingMessage(Object m) { 
     if (m instanceof String){ 
      Map<String,Object> headers=new HashMap<>(); 
      headers.put(Exchange.HTTP_URI, (String)m); 
      headers.put(Exchange.HTTP_METHOD, "GET"); 
      return super.onTransformOutgoingMessage(new CamelMessage(null,headers)); 
     } 
     return super.onTransformOutgoingMessage(m); 
    } 

    @Override 
    public void onRouteResponse(Object m) { 
     if (m instanceof CamelMessage){ 
      CamelMessage message=(CamelMessage) m; 
      System.out.println("Response: " + message.getBodyAs(String.class, getCamelContext())); 
      System.out.println("Code: " + message.headers().get(Exchange.HTTP_RESPONSE_CODE).get()); 
     } 
    } 

所以我建議第二種方法,因爲你只需要創建一個Actor和一個調度程序

+0

謝謝,我給第二種方法去了。 – prio