首页 > 数据库 >.Net6 + GraphQL + MongoDb 实现Subscription监听功能

.Net6 + GraphQL + MongoDb 实现Subscription监听功能

时间:2023-02-16 13:37:25浏览次数:48  
标签:MongoDb GraphQL Net6 new publishedPost post Post publishPost subscription

介绍

查询、添加、修改我们已经演示了,我们来看下订阅。

订阅大家可以理解为音乐软件, 我们用户 => 订阅音乐频道 <= 服务发送新的音乐通知到频道。 有新的通知进入频道后,频道会推送给客户。

这个东西就和Rxjs一样,在Angular客户端用起来也是一个效果。

正文

修改PostMutation.cs新增接口

    public async Task<AddPostPayload> PublishPost(
            [Service] DbContext db,
            [Service]ITopicEventSender sender,
            AddPostInput input,
            CancellationToken cancellationToken)
        {
            var entity = new Post()
            {
                Title = input.Title,
                Abstraction = "this is an introduction post for graphql",
                Content = "some random content for post 1",
                Author = input.Author,
                PublishedAt = DateTime.Now.AddDays(-2),
                Link = "http://link-to-post-1.html",
                Comments = new List<Comment>
                {
                    new() { CreatedAt = DateTime.Now, Content = "test  comment 03 for post 1", Name = "kindUser02" }
                },
            };

            // await db.Post.InsertOneAsync(entity, cancellationToken: cancellationToken);

            await sender.SendAsync(nameof(PublishPost), entity, cancellationToken);

            return new AddPostPayload(entity);
        }

新建PostSubscription文件

        [Subscribe]
        [Topic(nameof(PostMutation.PublishPost))]
        public Post OnPublishedPost(
            [EventMessage] Post publishedPost)
        {
            return publishedPost;
        }

修改Program

builder.Services
    .AddGraphQLServer()
    .AddQueryType<PostQuery>()
    .AddMutationType<PostMutation>()
    .AddSubscriptionType<PostSubscription>()
    .AddInMemorySubscriptions()
    .AddMongoDbFiltering()
    .AddMongoDbSorting()
    .AddMongoDbProjections()
    .AddMongoDbPagingProviders()
    .SetPagingOptions(new PagingOptions
    {
        MaxPageSize = 50,
        IncludeTotalCount = true
    });




var app = builder.Build();

app.UseHttpsRedirection();

app.UseWebSockets();

app.UseRouting().UseEndpoints(endpoints =>
{
    endpoints.MapGraphQL();
});

app.UseGraphQLVoyager("/graphql-voyager", new VoyagerOptions { GraphQLEndPoint = "/graphql" });

这时候我们去https://localhost:7145/graphql/调用接口,打开2个页面,

A页面调用subscription publishedPost,调用后客户端会进入订阅状态,等待消息

B页面调用mutation publishPost,发送消息

mutation publishPost {
  publishPost(input: { title:"titl2222e test", author:" author test "}) {
    post {
      id
    }
  }
}

subscription publishedPost {
   onPublishedPost {
     id
     title
   } 
}
高级用法

修改PostSubscription.cs

        [Subscribe(With = nameof(OnPublishedStream))]
        //[Subscribe]
        //[Topic(nameof(PostMutation.PublishPost))]
        public Post OnPublishedPost(
            [EventMessage] Post publishedPost)
        {
            return publishedPost;
        }

        public async IAsyncEnumerable<Post> OnPublishedStream(
            [Service] ITopicEventReceiver eventReceiver, [EnumeratorCancellation] CancellationToken cancellationToken)
        {
            var sourceStream =
                await eventReceiver.SubscribeAsync<string, Post>(nameof(PostMutation.PublishPost), cancellationToken);

            // 这里理解为去请求数据库拿历史消息
            yield return new Post()
            {
                Title = "subscription Title",
                Abstraction = "this is an introduction post for graphql",
                Content = "some random content for post 1",
                Author = "subscription Author",
                PublishedAt = DateTime.Now.AddDays(-2),
                Link = "http://link-to-post-1.html",
                Comments = new List<Comment>
                {
                    new() { CreatedAt = DateTime.Now, Content = "test  comment 03 for post 1", Name = "kindUser02" }
                },
            };


            await Task.Delay(5000, cancellationToken);

            await foreach (Post post in sourceStream.ReadEventsAsync())
            {
                yield return post;
            }
        }

这时候我们去https://localhost:7145/graphql/调用接口,打开2个页面,

A页面调用subscription publishedPost,调用后客户端会立马收到消息subscription Title这个是等于是历史消息,然后会继续保持订阅状态。当mutation publishPost调用后会收到发送的消息

B页面调用mutation publishPost,发送消息。

mutation publishPost {
  publishPost(input: { title:"titl2222e test", author:" author test "}) {
    post {
      id
    }
  }
}

subscription publishedPost {
   onPublishedPost {
     id
     title
   } 
}

结语

本系列主要将GraphQL的使用,示例项目不能应用于生产,后续发一些GraphQL库出来讲解生产中的实际应用

联系作者:加群:867095512 @MrChuJiu

标签:MongoDb,GraphQL,Net6,new,publishedPost,post,Post,publishPost,subscription
From: https://www.cnblogs.com/MrChuJiu/p/17126311.html

相关文章

  • .Net6 WebApi中集成FluentValidation.AspNetCore的用法
    一、首先在nuget管理器中添加FluentValidation.AspNetCore包 二、添加验证类并继承AbstractValidator<T>,T为原始参数类,在验证类的构造函数中添加验证内容  三、......
  • MongoDB连接字符串的URI格式
    两种的连接字符串格式1.标准的连接格式mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]](1)单机连接格式mongodb://user......
  • .Net Core(.Net6)创建grpc
    1.环境要求.Net6,VisualStudio2019以上官方文档:https://learn.microsoft.com/zh-cn/aspnet/core/tutorials/grpc/grpc-startNetFramework版本:https://www.cnblo......
  • .Net6对AOP的多种支持之IAsyncActionFilter
    环境:  .Net6  windows10  Web项目 ps:Log4net写入到文件以及写入到数据库中开发工具:Vs2022IAsyncActionFilter(日志异步实现) IAsynctionFilter概念......
  • .NET6+WebApi+Vue 前后端分离后台管理系统(一)
    概述项目是用的NET6webapi搭建一个前后端分离的后端管理框架,项目分为:表示层、业务层、数据访问层、数据存储层。 Common:公共组件层,存放一些公共的方法。Model:实体Mod......
  • .Net Core(.Net6)创建grpc
    1.环境要求.Net6,VisualStudio2019以上官方文档:https://learn.microsoft.com/zh-cn/aspnet/core/tutorials/grpc/grpc-startNetFramework版本:https://www.cnblog......
  • .NET6 API 部署标准流程
    一、安装dotnet环境#第一步:将Microsoft包签名密钥添加到受信任密钥列表,并添加Microsoft包存储库sudorpm-Uvhhttps://packages.microsoft.com/config/centos/7/packa......
  • Mongodb数据库用户角色
    一、Mongodb数据库用户角色?MongoDB采用基于角色的访问控制(RBAC)来确定用户的访问。授予用户一个或多个角色,确定用户对MongoDB资源的访问权限和用户可以执行哪些操作。......
  • MongoDB 用户名密码登录 认证登陆
    mongo--port27017-u"adminUser"-p"adminPass"--authenticationDatabase"admin"[root@usdpvnode3mongodb]#catdocker-compose.ymlversion:'2'services:mong......
  • mongodb 命令行mongod启动报错
    abouttoforkchildprocess,waitinguntilserverisreadyforconnections.forkedprocess:3560ERROR:childprocessfailed,exitedwitherrornumber1Tose......