Implementation of nginx version of microservice architecture

Kejun cocoa 2020-11-07 20:37:39
implementation nginx version microservice architecture


One 、 brief introduction
         In the last article 《 A brief introduction to the true face of Lushan and its technology stack 》 in , We've explored the context of microservices , The technology stack needed to realize microservice architecture is also mentioned , Today we're starting to implement a microservice , Of course, this implementation is a simplified version , In this version, it doesn't involve Docker、K8S Wait for something , We evolved , Today's issue is just to achieve a NGINX Version of the microservice function .

       1、 explain
             There are too many technologies involved in microservice architecture , We can't discuss it completely in another article , therefore , Let's talk about it in multiple phases , Each issue advances the relevant technology , then , It evolved step by step . If you are Daniel , You can just skip , Because these things are relative to you , This is too easy . In particular , All the code here has been tested , So you can use .

       2、 development environment
            
Here's the development environment , Needless to say , All very simple. , It's easy to see .
            (1)、 development tool :Visual Studio 2019
            (2)、 development language :C#
            (3)、 Development platform :Net Core3.1, Cross platform .
            (4)、 Gateway service :NGINX, Focus on high performance gateways .

        3、 Today's goal
              Our goal today is to build a system based on Nginx Gateway implementation , The service instance does not have any container containment , It's just an implementation of such an architecture hosted by independent processes .
             

Two 、 Microservice architecture NGINX Version implementation
           
          Before the article begins , We still want to briefly explain . The last document 《 A brief introduction to the true face of Lushan and its technology stack 》 We said , There are three versions of microservices , Namely : Monomer architecture 、 Vertically split design and microservices , be based on SOA Let's not discuss . Actually , There is no essential difference between the second edition and the first one , It's all monomer architecture , therefore , Let's simply implement the version of microservices today , Because it involves a lot of Technology , I have divided the version of microservice into several versions , Today is the simplest .

          Today we are mainly talking about based on NGINX Distributed implementation 、 Advantages and disadvantages of microservice architecture , The code for each project is posted separately , The logic is simple , Because we focus on Architecture , Let's start .

        1、 Our solution , contain 5 A project .

             (1)、PatrickLiu.MicroService.Client(ASP.NET CORE MVC), Client applications .
                         The project is simple , There are almost no changes , It's just here to access the service instance .
                           

                           1)、startup.cs The only code added to the class

 1 public class Startup
 2  {
 3
 4 /// <summary>
 5 /// Register the service into the container .
 6 /// </summary>
 7 /// <param name="services"></param>
 8 public void ConfigureServices(IServiceCollection services)
 9  {
10 services.AddSingleton<IUserService, UserService>();
11  }
12 }

                           2)、HomeController.cs Class code                                 

 1 public class HomeController : Controller
 2  {
 3 private readonly ILogger<HomeController> _logger;
 4 private readonly IUserService _userService;
 5 private static int index;
 6
 7 /// <summary>
 8 /// Initializes a new instance of the type .
 9 /// </summary>
10 /// <param name="logger"> Injection log object .</param>
11 /// <param name="userService"> Inject user service objects .</param>
12 public HomeController(ILogger<HomeController> logger, IUserService userService)
13  {
14 _logger = logger;
15 _userService = userService;
16  }
17
18 /// <summary>
19 /// home page .
20 /// </summary>
21 /// <returns></returns>
22 public IActionResult Index()
23  {
24 #region 1、 Monomer architecture
25
26 //this.ViewBag.Users = _userService.UserAll();
27
28 #endregion
29
30 #region 2、 Distributed architecture
31
32 #region 2.1、 Direct access to service instances
33
34 //string url = string.Empty;
35 //url = "http://localhost:5726/api/users/all";
36 //url = "http://localhost:5726/api/users/all";
37 //url = "http://localhost:5726/api/users/all";
38
39 #endregion
40
41 #region adopt Ngnix Gateway access service instance , Default rotation training .
42
43 string url = "http://localhost:8080/api/users/all";
44
45 #endregion
46
47 string content = InvokeAPI(url);
48 this.ViewBag.Users = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<User>>(content);
49 Console.WriteLine($"This is {url} Invoke.");
50
51 #endregion
52
53 return View();
54  }
55
56
57 /// <summary>
58 ///
59 /// </summary>
60 /// <param name="url"></param>
61 /// <returns></returns>
62 public static string InvokeAPI(string url)
63  {
64 using (HttpClient client = new HttpClient())
65  {
66 HttpRequestMessage message = new HttpRequestMessage();
67 message.Method = HttpMethod.Get;
68 message.RequestUri = new Uri(url);
69 var result = client.SendAsync(message).Result;
70 string conent = result.Content.ReadAsStringAsync().Result;
71 return conent;
72  }
73  }
74  }
75 }

                          3)、Index.cshtml View code

 1 @{
 2 ViewData["Title"] = "Home Page";
 3 }
 4
 5 <div class="text-center">
 6 <h1 class="display-4">Welcome</h1>
 7 <ul>
 8  @{
 9
10 foreach (var item in ViewBag.Users)
11  {
12 <li>@item.ID --@item.Name --@item.Role </li>
13  }
14  }
15 </ul>
16 <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
17 </div>


             (2)、PatrickLiu.MicroService.Interfaces(NETCORE The class library project ), Define the service interface .
                          The project is simple , Only one interface type is defined , name :IUserService.cs.
                         

  IUserService Code for

 1 using PatrickLiu.MicroService.Models;
 2 using System.Collections.Generic;
 3
 4 namespace PatrickLiu.MicroService.Interfaces
 5 {
 6 /// <summary>
 7 /// User service interface definition .
 8 /// </summary>
 9 public interface IUserService
10  {
11 /// <summary>
12 /// Find the user instance object of the specified primary key .
13 /// </summary>
14 /// <param name="id"> User's primary key .</param>
15 /// <returns> Return the found user instance object .</returns>
16 User FindUser(int id);
17
18 /// <summary>
19 /// Get the instance collection of all users .
20 /// </summary>
21 /// <returns> Return all user instances .</returns>
22 IEnumerable<User> UserAll();
23  }
24 }


             (3)、PatrickLiu.MicroService.Models (NETCORE The class library project ), Define entity class model .
                         The project is simple , Only one entity type is defined , Class name :User.cs.
                        

                         User.cs Code for
                        

 1 using System;
 2
 3 namespace PatrickLiu.MicroService.Models
 4 {
 5 /// <summary>
 6 /// The user model .
 7 /// </summary>
 8 public class User
 9  {
10 /// <summary>
11 /// Get or set the user primary key .
12 /// </summary>
13 public int ID { get; set; }
14
15 /// <summary>
16 /// Get or set the user name .
17 /// </summary>
18 public string Name { get; set; }
19
20 /// <summary>
21 /// Get or set the user account name .
22 /// </summary>
23 public string Account { get; set; }
24
25 /// <summary>
26 /// Get or set the user password .
27 /// </summary>
28 public string Password { get; set; }
29
30 /// <summary>
31 /// Get or set the user's email address .
32 /// </summary>
33 public string Email { get; set; }
34
35 /// <summary>
36 /// Get or set the user role .
37 /// </summary>
38 public string Role { get; set; }
39
40 /// <summary>
41 /// Get or set the login time of the user .
42 /// </summary>
43 public DateTime LoginTime { get; set; }
44  }
45 }



             (4)、PatrickLiu.MicroService.Services(NetCore The class library project ), Implementation interface type .
                         The project is simple , Only one type is defined , Realization IUserService Interface , Class name :UserService.cs.
                        

UserService.cs Code for

 1 using PatrickLiu.MicroService.Interfaces;
 2 using PatrickLiu.MicroService.Models;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6
 7 namespace PatrickLiu.MicroService.Services
 8 {
 9 /// <summary>
10 /// The implementation type that implements the user service interface .
11 /// </summary>
12 public class UserService : IUserService
13  {
14 private IList<User> dataList;
15
16 /// <summary>
17 /// Initializing an instance of a type
18 /// </summary>
19 public UserService()
20  {
21 dataList = new List<User>()
22 { new User {ID=1,Name=" huang feihong ",Account="HuangFeiHong",Password="HuangFeiHong123456",Email="huangFeiHong@sina.com", Role="Admin", LoginTime=DateTime.Now },
23 new User {ID=2,Name=" Hongxiguan ",Account="HongXiGuan",Password="HongXiGuan54667",Email="HongXiGuan@sina.com", Role="Admin", LoginTime=DateTime.Now.AddDays(-5) },
24 new User {ID=3,Name=" Fang Shiyu ",Account="FangShiYu",Password="FangShiYu112233",Email="fangShiYu@163.com", Role="Admin", LoginTime=DateTime.Now.AddDays(-30) },
25 new User {ID=4,Name=" Miao Cuihua ",Account="MiaoCuiHua",Password="MiaoCuiHua887766",Email="miaoCuiHua@sohu.com", Role="Admin", LoginTime=DateTime.Now.AddDays(-90) },
26 new User {ID=5,Name=" Yan Yongchun ",Account="YanYongChun",Password="YanYongChun09392",Email="yanYongChun@263.com", Role="Admin", LoginTime=DateTime.Now.AddMinutes(-50) }};
27  }
28
29 /// <summary>
30 /// Find the user instance object of the specified primary key .
31 /// </summary>
32 /// <param name="id"> User's primary key .</param>
33 /// <returns> Return the found user instance object .</returns>
34 public User FindUser(int id)
35  {
36 return dataList.FirstOrDefault(user => user.ID == id);
37  }
38
39 /// <summary>
40 /// Get the instance collection of all users .
41 /// </summary>
42 /// <returns> Return all user instances .</returns>
43 public IEnumerable<User> UserAll()
44  {
45 return dataList;
46  }
47  }
48 }

             
             (5)、PatrickLiu.MicroService.ServiceInstance(ASP.NET CORE WEB API project ).
                          The project is simple , Reference the other three projects , Make Restfull API, The client can access .
                         Reference project :PatrickLiu.MicroService.Interfaces
                                          PatrickLiu.MicroService.Services
                                          PatrickLiu.MicroService.Models
                         

1)、Startup.cs Code for

 1 public class Startup
 2  {
 3
 4 /// <summary>
 5 ///
 6 /// </summary>
 7 /// <param name="services"></param>
 8 public void ConfigureServices(IServiceCollection services)
 9  {
10  services.AddControllers();
11 services.AddSingleton<IUserService, UserService>();
12  }
13 }

2)、Program.cs Code for

 1 public class Program
 2  {
 3 public static void Main(string[] args)
 4  {
 5 new ConfigurationBuilder()
 6  .SetBasePath(Directory.GetCurrentDirectory())
 7 .AddCommandLine(args)// Support command line 
 8  .Build();
 9
10  CreateHostBuilder(args).Build().Run();
11  }
12
13 public static IHostBuilder CreateHostBuilder(string[] args) =>
14  Host.CreateDefaultBuilder(args)
15 .ConfigureWebHostDefaults(webBuilder =>
16  {
17 webBuilder.UseStartup<Startup>();
18  });
19 }

3)、UsersController.cs Code for

 1 /// <summary>
 2 /// User API type .
 3 /// </summary>
 4 [Route("api/[controller]")]
 5  [ApiController]
 6 public class UsersController : ControllerBase
 7  {
 8 #region Private field
 9
10 private readonly ILogger<UsersController> _logger;
11 private readonly IUserService _userService;
12 private IConfiguration _configuration;
13
14 #endregion
15
16 #region Constructors
17
18 /// <summary>
19 /// Initializes a new instance of the type .
20 /// </summary>
21 /// <param name="logger"> Loggers .</param>
22 /// <param name="userService"> User service interface .</param>
23 /// <param name="configuration"> Configure the service .</param>
24 public UsersController(ILogger<UsersController> logger, IUserService userService, IConfiguration configuration)
25  {
26 _logger = logger;
27 _userService = userService;
28 _configuration = configuration;
29  }
30
31 #endregion
32
33 #region Example method
34
35 /// <summary>
36 /// Get a record
37 /// </summary>
38 /// <param name="id"></param>
39 /// <returns></returns>
40  [HttpGet]
41 [Route("Get")]
42 public User Get(int id)
43  {
44 return _userService.FindUser(id);
45  }
46
47 /// <summary>
48 /// Get all the records .
49 /// </summary>
50 /// <returns></returns>
51  [HttpGet]
52 [Route("All")]
53 //[Authorize]
54 public IEnumerable<User> Get()
55  {
56 Console.WriteLine($"This is UsersController {this._configuration["port"]} Invoke");
57
58 return this._userService.UserAll().Select((user => new User
59  {
60 ID = user.ID,
61 Name = user.Name,
62 Account = user.Account,
63 Password = user.Password,
64 Email = user.Email,
65 Role = $"{this._configuration["ip"]}:{this._configuration["port"]}",
66 LoginTime = user.LoginTime
67  })); ;
68  }
69
70 /// <summary>
71 /// timeout handler
72 /// </summary>
73 /// <returns></returns>
74  [HttpGet]
75 [Route("Timeout")]
76 public IEnumerable<User> Timeout()
77  {
78 Console.WriteLine($"This is Timeout Start");
79 // timeout .
80 Thread.Sleep(3000);
81
82 Console.WriteLine($"This is Timeout End");
83
84 return this._userService.UserAll().Select((user => new User
85  {
86 ID = user.ID,
87 Name = user.Name,
88 Account = user.Account,
89 Password = user.Password,
90 Email = user.Email,
91 Role = $"{this._configuration["ip"]}:{this._configuration["port"]}",
92 LoginTime = user.LoginTime
93  })); ;
94  }
95
96 #endregion
97 }

         

         2、 Compile the project , Start four service instances .
                These four service examples are PatrickLiu.MicroService.ServiceInstance Examples of projects , perform dotnet The command should be in the current directory .
                My catalog :E:\Visual Studio 2019\Project\SourceCode\PatrickLiu.MicroService\PatrickLiu.MicroService.ServiceInstance\bin\Debug\netcoreapp3.1
              (1)、dotnet PatrickLiu.MicroService.ServiceInstance.dll --urls="http://*:5726" --ip="127.0.0.1" --port=5726

                        

                         You can visit WebAPI Address , Verify success .
                         Address :http://localhost:5726/api/users/all
                         The effect is as shown in the picture :
          
              
              (2)、dotnet PatrickLiu.MicroService.ServiceInstance.dll --urls="http://*:5727" --ip="127.0.0.1" --port=5727

                         

                         You can visit WebAPI Address , Verify success .
                         Address :http://localhost:5727/api/users/all
                         The effect is as shown in the picture :

             (3)、dotnet PatrickLiu.MicroService.ServiceInstance.dll --urls="http://*:5728" --ip="127.0.0.1" --port=5728

                        

                         You can visit WebAPI Address , Verify success .
                         Address :http://localhost:5728/api/users/all
                         The effect is as shown in the picture :

             (4)、dotnet PatrickLiu.MicroService.ServiceInstance.dll --urls="http://*:5729" --ip="127.0.0.1" --port=5729

                        

                         You can visit WebAPI Address , Verify success .
                         Address :http://localhost:5729/api/users/all
                         The effect is as shown in the picture :

         3、 download NGINX Service components , Default download Windows edition .
     
                  
                        Official website : http://nginx.org/en/download.html


         4、 Deploy NGINX The server .
                   Copy the downloaded file to a directory without Chinese , Just unzip the file .
                   My storage directory :D:\Programs\MicroServices
                   
         5、 modify NGINX.CONF file .               
      
                 Modify the directory D:\Programs\MicroServices\Nginx-1.18.0\conf Profile under . file name :nginx.conf
                  
               The added configuration is as follows :

 1  upstream MicroService{
 2 server localhost:5726;
 3 server localhost:5727;
 4 server localhost:5728;
 5 server localhost:5729;
 6  }
 7
 8 server {
 9 listen 8080;
10  server_name localhost;
11
12 location / {
13 proxy_pass http://MicroService;
14  }
15 }



         6、 start-up Nginx The server .
                 Be careful : I was in Nginx Under the current directory .
                 Start nginx
                 
                NGINX Port default :80, I changed it to 8080, No hints , It usually starts normally .

                You can visit NGINX Address , verification NGINX Whether it is configured and started successfully .
                Address :http://localhost:8080
                The effect is as shown in the picture :

        7、 Open the browser , Enter the address :http://localhost:8080/api/users/all, Refresh the page many times , You'll see the change . We've implemented distributed 、 Load balancing .
                Pictured :5726 port
                    

               Pictured :5727 port
                   

               Pictured :5728 port
                    

               Pictured :5729 port
                    

          8、 We test NGINX High availability and scalability , The following conclusions are drawn .
     (1)、Nginx The client configuration is simple , Direct access Nginx The gateway address will be routed to the registration service instance .
                   (2)、 If the service instance is offline or abnormal , Can automatically detect conditions , You can skip it next time , There's no need for human participation .
                   (3)、 If the system adds new service instances ,Nginx Can't automatically discover , You need to manually modify the configuration file , And then restart , Can only be .
Because of the shortcomings of the third point , Is the biggest drawback of our version , We can't do these things all the time in a huge system . Unable to automatically discover services , We need to continue to improve , That's the service registry discovery center .

3、 ... and 、  Conclusion
   
      Okay , That's it for today , This is a very simple architecture implementation between distributed and microservices , Although it's very simple , But what we want to express and what we want to get, we have got . Everything goes from simple to complicated , Next issue , Let's continue with our evolution of microservices . Efforts! , Make a little progress every day .

版权声明
本文为[Kejun cocoa]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple