dotnet core微服務框架Jimu ~ 瀏覽和釋出新聞微服務

Flamesky發表於2024-11-13

提供新聞瀏覽和釋出服務

有 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();
                }
            }
        }
    }
}

相關文章