使用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 ...
随机推荐
- Tornado创建一个web服务
import tornado.web import tornado.ioloop import tornado.httpserver import tornado.options import con ...
- redis get乱码
- 记一次mac下使用mamp集成环境配置lumen项目自定义域名遇到的花样问题
1.安装好mamp集成环境,自行百度. 2.从公司项目版本库里将项目克隆到本地. 好了,开始配置自定义域名来访问项目,以下是遇到的问题集锦... 1.web服务器使用的nginx,配置完域名访问报40 ...
- openstack 王者归来学习笔记
rpc.call方法执行的流程:(下次看代码的时候可以根据这流程来看,注意:由于rpc服务器和客户端具有很松的耦合性,因此以上步骤并不是绝对的.) 1.rpc服务器定义和启动rpc服务 2.rpc服务 ...
- Django高级实战 开发企业级问答网站完整
资源获取链接点击这里 Django高级实战 开发企业级问答网站 从实际需求分析开始,实现当今主流知识问答应用的功能,包括动态.文章.问答.私信.消息通知.搜索.个人中心,打造企业级知识问答网站,由此全 ...
- java多线程系列 目录
Java多线程系列1 线程创建以及状态切换 Java多线程系列2 线程常见方法介绍 Java多线程系列3 synchronized 关键词 Java多线程系列4 线程交互(wait和 ...
- IMPLEMENTATION - Entity Framework Anti Pattern - High Performance EF
Good about ORM Developer is free from building T-Sql on the database tier which is not their major a ...
- springboot 使用mysql(mybatis)
添加mysql依赖项 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifac ...
- XML文件的解析—DOM、SAX
一.DOM 解析 思路:获得Document对象,遍历其中节点获得需要的内容 要点: Document : DocuemntBuilderFactory --newDocumentBuilder - ...
- Shell脚本备份数据库(多库)
#!/bin/bashPATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbinexport PATH#数据库用户名dbuser ...