dotnet core微服务框架Jimu ~ 浏览和发布新闻微服务

提供新闻浏览和发布服务

有 3 个需要授权公开的 api:

  1. GetAllNews 获取所有新闻
  2. PostNews 发布新闻, 具有 admin 角色的会员才能发布新闻
  3. GetNews 根据 id 获取指定的新闻

1 声明接口,创建基于 .Net Core 6.0 的类库项目,命名为 News.IServices

1.1 添加 jimu 引用

Install-Package  Jimu

1.2 创建 dto 类

using System;
using System.Collections.Generic;
using System.Text;

namespace News.IServices
{
    public class News
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public string Director { get; set; }
        public string PostTime { get; set; }
        public string Content { get; set; }

    }
}

1.3 声明公开的微服务接口

微服务的定义规则:

  1. 必须继承 IJimuService 接口
  2. 声明路由属性 [JimuServiceRoute()]
  3. 方法添加属性 [JimuService()],该方法才会注册成公开的微服务

Jimu 支持异步方法, 如下面的 Register

下面 3 个方法,都设置 EnableAuthorization = true, 需要授权才能访问(即请求要带上 token),其中 PostNews 指定 Roles = "admin", 具有 admin 角色的会员才能调用该方法

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Jimu;

namespace News.IServices
{
    [JimuServiceRoute("/api/v1/news")]
    public interface INewsService : IJimuService
    {
        [JimuService(EnableAuthorization = true, CreatedBy = "grissom", CreatedDate = "2018-07-17", Comment = "get all news")]
        Task<List<News>> GetAllNews();

        [JimuService(EnableAuthorization = true, Roles = "admin", CreatedBy = "grissom", CreatedDate = "2018-07-17", Comment = "post news")]
        Task<string> PostNews(News news);

        [JimuService(EnableAuthorization = true, CreatedBy = "grissom", CreatedDate = "2018-07-17", Comment = "get specify news")]
        News GetNews(string id);
    }
}

2 实现接口,创建基于 .Net Core 6.0 的类库项目,命名为 News.Services

2.1 添加对接口项目 News.IServices 的引用

2.2 实现接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Jimu;

namespace News.IServices
{
    public class NewsService : INewsService
    {
        readonly ILogger _logger;
        readonly JimuPayload _jimuPayload;
        static List<News> _newsDb = new List<News>();
        static NewsService()
        {
            // mock some  news
            _newsDb.Add(new News { Id = Guid.NewGuid().ToString(), Director = "grissom", PostTime = DateTime.Now.ToString(), Title = "世界杯:法国夺冠啦!", Content = "头条:法国勇夺2018年世界杯冠军, 后面省略 1 万字" });
            _newsDb.Add(new News { Id = Guid.NewGuid().ToString(), Director = "grissom", PostTime = DateTime.Now.ToString(), Title = "Jimu 发布新版本", Content = "新闻社:Jimu(积木) 发布新版本,特点有,后面省略 1 万字" });
        }
        public NewsService(ILogger logger, JimuPayload jimuPayload)
        {
            _logger = logger;
            _jimuPayload = jimuPayload;
        }

        public Task<List<News>> GetAllNews()
        {
            _logger.Debug($"member: {_jimuPayload.Items["username"]} getallnews");
            return Task.FromResult(_newsDb);
        }

        public Task<string> PostNews(News news)
        {
            _logger.Debug($"member: {_jimuPayload.Items["username"]} post an news which title is: {news.Title}");

            news.PostTime = DateTime.Now.ToString();
            news.Id = new Guid().ToString();
            news.Director = _jimuPayload.Items["username"].ToString();
            _newsDb.Add(news);
            return Task.FromResult(news.Id);

        }

        public News GetNews(string id)
        {
            _logger.Debug($"member: {_jimuPayload.Items["username"]} getnews by id: {id}");
            var news = _newsDb.FirstOrDefault(x => x.Id == id);
            return news;
        }
    }
}

3 微服务的宿主服务器,创建基于 .Net Core 6.0 的控制台应用, 命名为 News.Server

3.1 添加对项目: News.Services 的引用

3.2 添加 jimu.server 和 Jimu.Common.Discovery.ConsulIntegration 引用

Install-Package  Jimu.Server
Install-Package  Jimu.Common.Discovery.ConsulIntegration

3.3 启动 jimu 服务代码

using System;
using Autofac;
using Jimu.Server;

namespace News.Server
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ServiceHostServerBuilder(new ContainerBuilder())
             .UseLog4netLogger()
             .LoadServices("News.IServices", "News.Services")
             .UseDotNettyForTransfer("127.0.0.1", 8002)
             .UseConsulForDiscovery("127.0.0.1", 8500, "JimuService", $"127.0.0.1:8002")
             .UseJoseJwtForOAuth<Jimu.DotNettyAddress>(new Jimu.Server.OAuth.JwtAuthorizationOptions
             {
                 SecretKey = "123456",
             });
            using (var host = builder.Build())
            {
                host.Run();
                while (true)
                {
                    Console.ReadKey();
                }
            }
        }
    }
}

 

posted @ 2024-11-13 20:13  Flamesky  阅读(292)  评论(2编辑  收藏  举报