orleans 2.0 进阶之自定义持久化储存

一丶简单介绍下目录结构和项目依赖,如图

orleans 2.0 进阶之自定义持久化储存_第1张图片

二丶主要核心自定义代码

1. 添加自定义实现类 CustomProvider

public class CustomProvider : IGrainStorage
    {
        public Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
        {
            throw new NotImplementedException();
        }

        public Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
        {
            if(grainType== "Grain.UserGrain")
            {
                var id = grainReference.GetPrimaryKeyLong();

                //模拟从数据库读出User
                var user = new UserState()
                {
                    MobilePhone = "124214214",
                    Name = "李四"
                };

                grainState.State = user;

            }
            return Task.CompletedTask;
        }

        public Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
        {

            if (grainType== "Grain.UserGrain")
            {
                var id = grainReference.GetPrimaryKeyLong();

                //模拟保存数据库


            }
            return Task.CompletedTask;
        }
    }

2. 在silo中注入代替默认实现

 .ConfigureServices(services =>
                   {
                       var providerName = "CustomProvider";
                       services.TryAddSingleton(sp =>
                           sp.GetServiceByName(ProviderConstants.DEFAULT_STORAGE_PROVIDER_NAME));

                       services.AddSingletonNamedService(providerName);
                   })

3. 在grain类上启用

 [StorageProvider(ProviderName = "CustomProvider")]

 

三丶运行结果如下

orleans 2.0 进阶之自定义持久化储存_第2张图片

 

 

示例代码下载地址:SimpleStorage

你可能感兴趣的:(技术)