共用方式為


Service Fabric Reliable Actors 類型序列化的注意事項

所有方法的引數、動作項目介面中每個方法所傳回之工作的結果類型,以及動作項目的狀態管理員中儲存的物件都必須可資料合約序列化。 這也適用於在 動作項目事件介面中定義的方法引數。 (動作項目事件介面方法一律會傳回無效)。

自訂資料類型

在此範例中,下列動作項目介面會定義一個方法,以傳回名為 VoicemailBox 的自訂資料類型:

public interface IVoiceMailBoxActor : IActor
{
    Task<VoicemailBox> GetMailBoxAsync();
}
public interface VoiceMailBoxActor extends Actor
{
    CompletableFuture<VoicemailBox> getMailBoxAsync();
}

此介面是由動作項目實作,其使用狀態管理員來儲存 VoicemailBox 物件︰

[StatePersistence(StatePersistence.Persisted)]
public class VoiceMailBoxActor : Actor, IVoicemailBoxActor
{
    public VoiceMailBoxActor(ActorService actorService, ActorId actorId)
        : base(actorService, actorId)
    {
    }

    public Task<VoicemailBox> GetMailboxAsync()
    {
        return this.StateManager.GetStateAsync<VoicemailBox>("Mailbox");
    }
}

@StatePersistenceAttribute(statePersistence = StatePersistence.Persisted)
public class VoiceMailBoxActorImpl extends FabricActor implements VoicemailBoxActor
{
    public VoiceMailBoxActorImpl(ActorService actorService, ActorId actorId)
    {
         super(actorService, actorId);
    }

    public CompletableFuture<VoicemailBox> getMailBoxAsync()
    {
         return this.stateManager().getStateAsync("Mailbox");
    }
}

在此範例中, VoicemailBox 物件會在下列情況進行序列化︰

  • 在動作項目執行個體與呼叫端之間傳輸物件。
  • 物件已儲存在狀態管理員,以保存到磁碟並複寫到其他節點。

Reliable Actor 架構會使用 DataContract 序列化。 因此,自訂資料物件與其成員必須使用 DataContractDataMember 屬性分別註解。

[DataContract]
public class Voicemail
{
    [DataMember]
    public Guid Id { get; set; }

    [DataMember]
    public string Message { get; set; }

    [DataMember]
    public DateTime ReceivedAt { get; set; }
}
public class Voicemail implements Serializable
{
    private static final long serialVersionUID = 42L;

    private UUID id;                    //getUUID() and setUUID()

    private String message;             //getMessage() and setMessage()

    private GregorianCalendar receivedAt; //getReceivedAt() and setReceivedAt()
}
[DataContract]
public class VoicemailBox
{
    public VoicemailBox()
    {
        this.MessageList = new List<Voicemail>();
    }

    [DataMember]
    public List<Voicemail> MessageList { get; set; }

    [DataMember]
    public string Greeting { get; set; }
}
public class VoicemailBox implements Serializable
{
    static final long serialVersionUID = 42L;
    
    public VoicemailBox()
    {
        this.messageList = new ArrayList<Voicemail>();
    }

    private List<Voicemail> messageList;   //getMessageList() and setMessageList()

    private String greeting;               //getGreeting() and setGreeting()
}

下一步