基础准备


1.创建asp.net core Web 应用程序选择Api

2.appsettings.json 配置consul服务器地址,以及本机ip和端口号信息

{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"Consul": {
"IP": "127.0.0.1",
"Port": "" },
"Service": {
"Name": "zyz"
},
"ip": "localhost",
"port": "", "AllowedHosts": "*"
}

3.程序入口(program.cs)配置useurls,ip和port从配置文件(或者命令行中)读取(命令行启动方式:dotnet ConsulServer.dll --ip localhost --port 8644)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; namespace ConsulServer
{
public class Program
{ public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
} public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
var config = new ConfigurationBuilder().AddCommandLine(args)
.Build();//获取配置信息
return WebHost.CreateDefaultBuilder(args)
.UseUrls($"http://{ config["ip"]}:{config["port"]}")//配置ip地址和端口地址
.UseStartup<Startup>();
} }
}

4.配置基础数据,并且调用注册consul接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Consul;
using ConsulServer.ConsulApi;
using ConsulServer.entity;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; namespace ConsulServer
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
{ if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
////配置信息单例
//ConfigSingleton.setConfigSingleton(Configuration); app.UseMvc(); ConsulEntity consulEntity = new ConsulEntity
{
ip = Configuration["ip"],
port = int.Parse(Configuration["port"] ),
ServiceName = "zyz",
ConsulIP = Configuration["Consul:IP"],
ConsulPort = Convert.ToInt32(Configuration["Consul:Port"])
};
app.RegisterConsul(lifetime, consulEntity);
} }
}

5.配置注册信息

using Consul;
using ConsulServer.entity;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace ConsulServer.ConsulApi
{
/// <summary>
/// consul
/// </summary>
public static class AppBuilderExtensions
{ /// <summary>
/// 注册consul
/// </summary>
/// <param name="app"></param>
/// <param name="lifetime"></param>
/// <param name="serviceEntity"></param>
/// <returns></returns>
public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IApplicationLifetime lifetime, ConsulEntity serviceEntity)
{
//consul地址
Action<ConsulClientConfiguration> configClient = (consulConfig) =>
{
consulConfig.Address = new Uri($"http://{serviceEntity.ConsulIP}:{ serviceEntity.ConsulPort}");
consulConfig.Datacenter = "dc1";
};
//建立连接
var consulClient = new ConsulClient(configClient);
var httpCheck = new AgentServiceCheck()
{
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(),//服务启动多久后注册
Interval = TimeSpan.FromSeconds(),//健康监测
HTTP = string.Format($"http://{serviceEntity.ip}:{serviceEntity.port}/api/health"),//心跳检测地址
Timeout = TimeSpan.FromSeconds()
};
//注册
var registrtion = new AgentServiceRegistration()
{ Checks = new[] { httpCheck },
ID = "zyzService" + Guid.NewGuid().ToString(),//服务编号不可重复
Name = serviceEntity.ServiceName,//服务名称
Address = serviceEntity.ip,//ip地址
Port = serviceEntity.port//端口 };
//注册服务
consulClient.Agent.ServiceRegister(registrtion); return app;
} }
}

6.以命令行启动程序查看consul(dotnet ConsulServer.dll --ip localhost --port 8644)

快速入口:微服务(入门一):netcore安装部署consul

快速入口: 微服务(入门二):netcore通过consul注册服务

快速入口: 微服务(入门三):netcore ocelot api网关结合consul服务发现

快速入口:微服务(入门四):identityServer的简单使用(客户端授权)

 

微服务(入门二):netcore通过consul注册服务的更多相关文章

  1. 微服务入门二:SpringCloud(版本Hoxton SR6)

    一.什么是SpringCloud 1.官方定义 1)官方定义:springcloud为开发人员提供了在分布式系统中快速构建一些通用模式的工具(例如配置管理.服务发现.断路器.智能路由.微代理.控制总线 ...

  2. 微服务架构 | 3.4 HashiCorp Consul 注册中心

    目录 前言 1. Consul 基础知识 1.1 Consul 是什么 1.2 Consul 的特点 2. 安装并运行 Consul 服务器 2.1 下载 Consul 2.2 运行 Consul 服 ...

  3. Asp.net core 向Consul 注册服务

    Consul服务发现的使用方法:1. 在每台电脑上都以Client Mode的方式运行一个Consul代理, 这个代理只负责与Consul Cluster高效地交换最新注册信息(不参与Leader的选 ...

  4. 建立eureka服务和客户端(客户端获取已经注册服务)

    1. 新建sping boot eureka server 新建立spring starter  project 修改pom.xml文件 在parent后追加 <dependencyManage ...

  5. 1、微服务--为什么有consul,consul注册,心跳检测,服务发现

    一.为什么有consul? 在微服务,每1个服务都是集群式的,订单服务在10台服务器上都有,那么用户的请求到达,获取哪台服务器的订单服务呢?如果10台中的有的订单服务挂了怎么办?10台服务器扛不住了, ...

  6. 微服务入门三:SpringCloud Alibaba

    一.什么是SpringCloud Alibaba 1.简介 1)简介 阿里云未分布式应用开发提供了一站式解决方案.它包含了开发分布式应用程序所需的所有组件,使您可以轻松地使用springcloud开发 ...

  7. Spring Cloud Consul 实现服务注册和发现

    Spring Cloud 是一个基于 Spring Boot 实现的云应用开发工具,它为基于 JVM 的云应用开发中涉及的配置管理.服务发现.断路器.智能路由.微代理.控制总线.全局锁.决策竞选.分布 ...

  8. SpringBoot系列: 使用 consul 作为服务注册组件

    本文基本上摘自纯洁的微笑的博客 http://www.ityouknow.com/springcloud/2018/07/20/spring-cloud-consul.html . 感谢作者的付出. ...

  9. 【SpringCloud】consul注册中心注册的服务为内网(局域网)IP

    一.前因 最近在做公司的一个微服务项目,技术架构为spring cloud + consul + SSM. 当我写完一个功能要在本地测试时,发现服务运行成功,但是前后端联调报500错误. 当时的第一个 ...

随机推荐

  1. ambari安装集群下安装kafka manager

    简介: 不想通过kafka shell来管理kafka已创建的topic信息,想通过管理页面来统一管理和查看kafka集群.所以选择了大部分人使用的kafka manager,我一共有一台主机mast ...

  2. ajax 原生态和jquery封装区别

    一.原生态 var xmlHttp = false; try{ if( xmlHttp && xmlHttp.readyState != 0 ){ xmlHttp.abort(); } ...

  3. MVC5 框架 配置 盘古分词

    2018.5.10日记 1.将sql数据库的内容添加到索引库中, public static readonly IndexManager instance; //静态构造函数,CLR只执行一次 sta ...

  4. PAT1136:A Delayed Palindrome

    1136. A Delayed Palindrome (20) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue ...

  5. 【原】fetch跨域请求附带cookie(credentials)

    HTTP访问控制 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS 解决跨域的方式有很多种,本文介绍" ...

  6. 剑指Offer_编程题之二维数组中的查找

    题目描述 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数.

  7. 设计模式(Design Patterns)Java版

    设计模式(Design Patterns) ——可复用面向对象软件的基础 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了 ...

  8. Spring Boot + Websocket + Thymeleaf + Lombok

    https://github.com/guillermoherrero/websocket 验证错误消息文件名字:是默认名ValidationMessages.properties,编译后存放在cla ...

  9. async 和 await 之异步编程的学习

    async修改一个方法,表示其为异步方法.而await表示等待一个异步任务的执行.js方面,在es7中开始得以支持:而.net在c#5.0开始支持.本文章将分别简单介绍他们在js和.net中的基本用法 ...

  10. 关于数据库报Packet for query is too large (1986748 > 1048576)(mysql写入数据过大)的解决办法

    方法2 (很妥协,很纠结的办法) 进入mysql server 在mysql 命令行中运行 set global max_allowed_packet = 2*1024*1024*10 然后关闭掉这此 ...