1.consul在微服務中的作用
consul主要做三件事:1.提供服務到ip的注冊
2.提供ip到服務地址的列表查詢
3.對提供服務方做健康檢查(定時調用服務方一個用於健康檢查的api接口 告訴消費方,服務方的服務是否還存在)
2.consul的下載及安裝
1.consul的下載地址 www..consul.io
2.consul的安裝 consul agent -dev 開發環境測試,在生產環境中要建立集群
3.consul的監控頁面 http://127.0.0.1:8500
3.相關代碼
新建一個Asp.net core Web應用程序,選擇Web API,名稱為MsgService
1.rest服務的准備
在Controller文件夾中 新建一個控制器ValueController ,rest服務的准備
namespace MsgService.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
再創建一個
namespace MsgService.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SMSController : ControllerBase
{
//發請求,報文體為{phoneNum:"110",msg:"aaaaaaaaaaaaa"},
[HttpPost(nameof(Send_MI))]
public void Send_MI(dynamic model)
{
Console.WriteLine($"通過小米短信接口向{model.phoneNum}發送短信{model.msg}");
}
[HttpPost(nameof(Send_LX))]
public void Send_LX(SendSMSRequest model)
{
Console.WriteLine($"通過聯想短信接口向{model.PhoneNum}發送短信{model.Msg}");
}
[HttpPost(nameof(Send_HW))]
public void Send_HW(SendSMSRequest model)
{
Console.WriteLine($"通過華為短信接口向{model.PhoneNum}發送短信{model.Msg}");
}
}
public class SendSMSRequest
{
public string PhoneNum { get; set; }
public string Msg { get; set; }
}
}
.net core連接consul install-package consul
2.服務的治理(服務的注冊 注銷 健康檢查)
在新創建的Web API程序的Startup.cs中完成服務的注冊
public void Configure(IApplicationBuilder app,IHostEnvironment env,IApplicationLifetime applicationTime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
string ip = Configuration["ip"];//獲取服務的ip地址
string port = Configuration["port"];//獲取服務的端口號
string serviceName = "MsgService";//服務的名稱
string serviceId = serviceName +Guid().NewGuid();//服務的ID 必須保證每一個服務的id是不一樣的
//consul的本地默認的ip及端口號為http://127.0.0.1:8500 可以自己進行設置
using(var consulClient = new ConsulClient(a=>{a.Address = new Uri("http://127.0.0.1:8500";a.DataCenter="dic1";)})){
AgentServiceRegistration asr = new AgentServiceRegistration();//創建一個服務代理的注冊者
asr.Address = ip;
asr.Port = port;
asr.ID = serviceId;
asr.Name = serviceName;
asr.Check = new AgentServiceCheck(){ //設置健康檢查間隔時間以及檢查地址
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//
HTTP = $"http://{ip}:{port}/api/Health",
Interval = TimeSpan.FromSeconds(10),
TimeOut = TimeSpan.FromSeconds(5)
};
//這是一個異步方法
consulClient.Agent.ServiceRegister(asr).wait();
}
//注銷服務
applicationTime.ApplicationStopped.Register(()=>{
using(var consulClient = new ConsulClient(a=>a.Address = new Uri("http://127.0.0.1:8500")))
{
//通過服務的Id完成服務的銷毀
consulClient.Agent.ServiceDeregister(serviceId).wait();
}
})
}
3.服務的發現
編寫服務消費者
創建一個.net core控制台程序或者web應用程序 ,在startup.cs中
app.run(async(context)=>{
using(var consulClient= new ConsulClient(a=>a.Address=new Uri("http://127.0.0.1:8500"))){
//客戶端負載均衡
var services = consulClient.Agent.Services().Result.Response.Values.Where(a=>a.Service.Equals("MsgService"));//找到服務名稱為MsgService的服務
//通過隨機數獲取一個隨機索引 去除索引為生成的隨機數的服務
Random r = new Random();
int index = r.Next(service.Count());
var service = services.ElementAt(index);
await context.Response.WriteAsync($"id={service.ID},name={service.Service},ip={service.Address},port={service.Port}");
//服務
using(HttpClient http = new HttpClient())
using(var httpContent = new StringContent("{phoneNum:'119',msg:'help'}", Encoding.UTF8, "application/json")){
var http.PostAsync($"http://{service.Address}:{service.Port}/api/SMS/Send_LX", httpContent).Result;
await context.Response.WriteAsync(result.StatusCode.ToString());
}
}
})