使用Consul 实现 MagicOnion(GRpc) 服务注册和发现
1.下载打开Consul
笔者是windows下面开发的(也可以使用Docker)。
官网下载windows的Consul
使用cmd窗口打开,输入consul agent -dev
访问默认127.0.0.1:8500就可以看到界面化的Consul
2.在服务端注册
接着上一篇
using Consul;
using Grpc.Core;
using GRPCServer.Entity;
using MagicOnion.Server;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace GRPCServer
{
public class Startup
{
public Startup(IConfiguration configuration)
{
this.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_2);
MagicOnionServiceDefinition service = MagicOnionEngine.BuildServerServiceDefinition(new MagicOnionOptions(true)
{
MagicOnionLogger = new MagicOnionLogToGrpcLogger()
});
Server server = new Server
{
Services = { service },
Ports = { new ServerPort(this.Configuration["Service:LocalIPAddress"], Convert.ToInt32(this.Configuration["Service:Port"]), ServerCredentials.Insecure) }
};
server.Start();
}
// 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();
}
app.UseMvc();
ServiceEntity serviceEntity = new ServiceEntity
{
IP = this.Configuration["Service:LocalIPAddress"],
Port = Convert.ToInt32(this.Configuration["Service:Port"]),
ServiceName = this.Configuration["Service:Name"],
ConsulIP = this.Configuration["Consul:IP"],
ConsulPort = Convert.ToInt32(this.Configuration["Consul:Port"])
};
var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{serviceEntity.ConsulIP}:{serviceEntity.ConsulPort}"));//请求注册的 Consul 地址
var httpCheck = new AgentServiceCheck()
{
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔,或者称为心跳间隔
HTTP = this.Configuration["Service:Examination"],//健康检查地址
Timeout = TimeSpan.FromSeconds(5)
};
var registration = new AgentServiceRegistration()
{
Checks = new[] { httpCheck },
ID = Guid.NewGuid().ToString(),
Name = serviceEntity.ServiceName,
Address = serviceEntity.IP,
Port = serviceEntity.Port,
Tags = new[] { $"urlprefix-/{serviceEntity.ServiceName}" }//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别
};
consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起)
lifetime.ApplicationStopping.Register(() =>
{
consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册
});
}
}
}
appsettings.json
{
"Service": {
"Name": "Test3",
"Port": "8083",
"LocalIPAddress": "192.168.1.8",
"Examination": "http://192.168.1.8:5000/api/Values"
},
"Consul": {
"IP": "127.0.0.1",
"Port": "8500"
}
}
3.客户端调用
using Consul;
using Grpc.Core;
using MagicOnion.Client;
using ServerDefinition;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
var aaa= AvaliableServices("Test3","").Result;
public static async Task<ServiceEntry[]> AvaliableServices(string name, string tags)
{
var services = new List<ServiceEntry>();
using (var client = new ConsulClient())
{
foreach (var tag in tags.Split(','))
{
var result = await client.Health.Service(name, !string.IsNullOrEmpty(tag) ? tag : null, true).ConfigureAwait(false);
foreach (var item in result.Response)
{
if (!services.Any(service => service.Node.Address == item.Node.Address
&& service.Service.Port == item.Service.Port))
{
services.Add(item);
}
}
}
//交集处理,仅取出完全匹配服务
foreach (var tag in tags.Split(','))
{
if (string.IsNullOrEmpty(tag))
{
continue;
}
var alsorans = services.Where(service => !service.Service.Tags.Contains(tag)).ToList();
foreach (var alsoran in alsorans)
{
services.Remove(alsoran);
}
}
}
return services.ToArray();
}
4.思考
这个时候我就能通过'Test3'来获得Test3的服务和接口。
但是我是使用的MagicOnion,还是没办法拿到我定义的方法SumAsync
怎么办?
1.引用ITest (让微服务之间有引用,不太好)
2.使用网关
5.预告
下一篇我会想法办法使他们能相互通讯(其实我还不知道怎么搞)
使用Consul 实现 MagicOnion(GRpc) 服务注册和发现的更多相关文章
- 微服务学习笔记(2)——使用Consul 实现 MagicOnion(GRpc) 服务注册和发现
原文:微服务学习笔记(2)--使用Consul 实现 MagicOnion(GRpc) 服务注册和发现 1.下载打开Consul 笔者是windows下面开发的(也可以使用Docker). 官网下载w ...
- 基于 Consul 实现 MagicOnion(GRpc) 服务注册与发现
0.简介 0.1 什么是 Consul Consul是HashiCorp公司推出的开源工具,用于实现分布式系统的服务发现与配置. 这里所谓的服务,不仅仅包括常用的 Api 这些服务,也包括软件开发过程 ...
- C#使用Consul集群进行服务注册与发现
前言 我个人觉得,中间件的部署与使用是非常难记忆的:也就是说,如果两次使用中间件的时间间隔比较长,那基本上等于要重新学习使用. 所以,我觉得学习中间件的文章,越详细越好:因为,这对作者而言也是一份珍贵 ...
- (8)ASP.NET Core3.1 Ocelot Consul服务注册与发现
1.服务注册与发现(Service Discovery) ●服务注册:我们通过在每个服务实例写入注册代码,实例在启动的时候会先去注册中心(例如Consul.ZooKeeper.etcd.Eureka) ...
- python与consul 实现gRPC服务注册-发现
背景 通过对gRPC的介绍我们知道,当正常启动服务后,我们只需要知道ip,port就可以进行gRPC的连接.可以想到,这种方式并不适合用于线上环境,因为这样直连的话就失去了扩展性,当需要多机部署的时候 ...
- Docker+Consul+Registrator 实现服务注册与发现
Docker+Consul+Registrator实现服务注册与发现 逻辑图 实现nginx节点自动化加入容器IP代理 1.三台Consul agent server作为高可用通过Consul Tem ...
- 分布式服务注册和发现consul 简要介绍
Consul是HashiCorp公司推出的开源工具,用于实现分布式系统的服务发现与配置.与其他分布式服务注册与发现的方案,Consul的方案更"一站式",内置了服务注册与发现框 架 ...
- Spring Cloud Consul 实现服务注册和发现
Spring Cloud 是一个基于 Spring Boot 实现的云应用开发工具,它为基于 JVM 的云应用开发中涉及的配置管理.服务发现.断路器.智能路由.微代理.控制总线.全局锁.决策竞选.分布 ...
- Spring Boot + Spring Cloud 构建微服务系统(一):服务注册和发现(Consul)
使用Consul提供注册和发现服务 什么是 Consul Consul 是 HashiCorp 公司推出的开源工具,用于实现分布式系统的服务发现与配置.与其它分布式服务注册与发现的方案,Consul ...
随机推荐
- Win7远程桌面:发生身份验证错误
下载并安装KB4103718补丁,安装完成后重启计算机 http://www.catalog.update.microsoft.com/Search.aspx?q=KB4103718 根据操作系统选择 ...
- UNIX 系统下退出 git commit 编辑器
如果是 Emacs 编辑器,输入 Ctrl X + Ctrl S(保存),再输入Ctrl X + Ctrl C(退出) 如果是VIM编辑器,输入 ESC + :wq UNIX 系统默认打开的是 Ema ...
- scrapy 爬取前程无忧
spider # -*- coding: utf-8 -*- import scrapy from Jobs.items import JobsItem class Job51spiderSpider ...
- 网址导航19A
[导航] KIM主页 265导航 好866 [名站] 百度 网易 腾讯 新华 中新 凤凰 [新闻] 联合早报 南方周末 澎湃新闻 [系统] 宋永志 蒲公英 技术员 装机网 系统之家 [软件] 星愿 ...
- Linode KVM安装Windows系统的设置方法
以前我们用老的Linode VPS主机的时候是采用的XEN架构的,如今我们新注册账户,以及新开的机器是KVM架构.根据后台的设置,我们看到好多网友有在LINODE中安装WINDOWS系统,理论上是可以 ...
- [模拟][NOIP2015]神奇的幻方
神奇的幻方 题目描述 幻方是一种很神奇的N∗ N矩阵:它由数字 1,2,3, … … , N ∗ N 构成,且每行.每列及两条对角线上的数字之和都相同. 当 N为奇数时,我们可以通过以下方法构建一个幻 ...
- 【漫画】程序员永远修不好的Bug——情人节
盼望着,盼望着,周五来了 情人节的脚步近了 一切都像热恋时的样子 飘飘然放开了买 购物车满起来了…… 不要指望着能在女生面前蒙混过关 是时候展现真正的技术了 这道坎过去了是情人节 过不去就是清明节了 ...
- S系统的不好的实践
多个项目 多个分支放在一个SVN里边维护,导致多股力量并行开发时候的代码覆盖的风险可能性很大,, 好的实践是维护独立的SVN,彼此分离开来
- 基于百词斩和扇贝单词的背单词APP软件测试
概述 背单词APP是非常受大学生青睐的手机应用,但它的发展尚未成熟,存在一些缺陷.我们决定深入地分析一组典型的背单词APP:百词斩(A产品).扇贝单词(B产品),寻找当前背单词APP中的提升空间.下面 ...
- strchr和strstr 函数
函数原型:extern char *strchr(char *str,char character) 参数说明:str为一个字符串的指针,character为一个待查找字符. 所在库名: ...