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

        }

    }

})