-
Notifications
You must be signed in to change notification settings - Fork 24
04.Server端配置
Mr Li edited this page Jul 8, 2021
·
3 revisions
Client端引入DotNetCoreRpc.Client包,并引入自定义的契约接口层
<PackageReference Include="DotNetCoreRpc.Server" Version="1.0.3" />
然后编写契约接口实现类,比如我的叫PersonService
//实现契约接口IPersonService
public class PersonService:IPersonService
{
private readonly ConcurrentDictionary<int, PersonDto> persons = new ConcurrentDictionary<int, PersonDto>();
public bool Add(PersonDto person)
{
return persons.TryAdd(person.Id, person);
}
public void Delete(int id)
{
persons.Remove(id,out PersonDto person);
}
//自定义Filter
[CacheFilter(CacheTime = 500)]
public PersonDto Get(int id)
{
return persons.GetValueOrDefault(id);
}
//自定义Filter
[CacheFilter(CacheTime = 300)]
public IEnumerable<PersonDto> GetAll()
{
foreach (var item in persons)
{
yield return item.Value;
}
}
}通过上面的代码可以看出,我自定义了Filter,这里的Filter并非Asp.Net Core框架定义的Filter,而是DotNetCoreRpc框架定义的Filter,自定义Filter的方式如下
//*要继承自抽象类RpcFilterAttribute
public class CacheFilterAttribute: RpcFilterAttribute
{
public int CacheTime { get; set; }
//*支持属性注入,可以是public或者private
//*这里的FromServices并非Asp.Net Core命名空间下的,而是来自DotNetCoreRpc.Core命名空间
[FromServices]
private RedisConfigOptions RedisConfig { get; set; }
[FromServices]
public ILogger<CacheFilterAttribute> Logger { get; set; }
public override async Task InvokeAsync(RpcContext context, RpcRequestDelegate next)
{
Logger.LogInformation($"CacheFilterAttribute Begin,CacheTime=[{CacheTime}],Class=[{context.TargetType.FullName}],Method=[{context.Method.Name}],Params=[{JsonConvert.SerializeObject(context.Parameters)}]");
await next(context);
Logger.LogInformation($"CacheFilterAttribute End,ReturnValue=[{JsonConvert.SerializeObject(context.ReturnValue)}]");
}
}以上代码基本上完成了对服务端业务代码的操作,接下来我们来看如何在Asp.Net Core中配置使用DotNetCoreRpc。打开Startup,配置如下代码既可
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IPersonService, PersonService>()
.AddSingleton(new RedisConfigOptions { Address = "127.0.0.1:6379", Db = 10 })
//*注册DotNetCoreRpcServer
.AddDotNetCoreRpcServer(options => {
//*确保添加的契约服务接口事先已经被注册到DI容器中
//添加契约接口
//options.AddService<IPersonService>();
//或添加契约接口名称以xxx为结尾的
//options.AddService("*Service");
//或添加具体名称为xxx的契约接口
//options.AddService("IPersonService");
//或扫描具体命名空间下的契约接口
options.AddNameSpace("IRpcService");
//可以添加全局过滤器,实现方式和CacheFilterAttribute一致
options.AddFilter<LoggerFilterAttribute>();
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//通过中间件的方式引入
//app.UseDotNetCoreRpc();
app.UseRouting();
app.UseEndpoints(endpoint => {
endpoint.Map("/", async context=>await context.Response.WriteAsync("server start!"));
//通过endpoint的方式引入
endpoint.MapDotNetCoreRpc();
});
}
}以上就是Server端简单的使用和配置,是不是感觉非常的Easy。附上可运行的Demo地址,具体编码可查看Demo.