微服务学习笔记(2)——使用Consul 实现 MagicOnion(GRpc) 服务注册和发现
原文:微服务学习笔记(2)——使用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.预告
下一篇我会想法办法使他们能相互通讯(其实我还不知道怎么搞)
微服务学习笔记(2)——使用Consul 实现 MagicOnion(GRpc) 服务注册和发现的更多相关文章
- 微服务学习笔记(1)——使用MagicOnion实现gRPC
原文:微服务学习笔记(1)--使用MagicOnion实现gRPC 1.什么是gRPC 官方文档:https://grpc.io/docs/guides/index.html 2.什么是MagicOn ...
- 基于 Consul 实现 MagicOnion(GRpc) 服务注册与发现
0.简介 0.1 什么是 Consul Consul是HashiCorp公司推出的开源工具,用于实现分布式系统的服务发现与配置. 这里所谓的服务,不仅仅包括常用的 Api 这些服务,也包括软件开发过程 ...
- 使用Consul 实现 MagicOnion(GRpc) 服务注册和发现
1.下载打开Consul 笔者是windows下面开发的(也可以使用Docker). 官网下载windows的Consul https://www.consul.io/ 使用cmd窗口打开,输入con ...
- SpringCloud微服务学习笔记
SpringCloud微服务学习笔记 项目地址: https://github.com/taoweidong/Micro-service-learning 单体架构(Monolithic架构) Mon ...
- Spring Cloud微服务学习笔记
Spring Cloud微服务学习笔记 SOA->Dubbo 微服务架构->Spring Cloud提供了一个一站式的微服务解决方案 第一部分 微服务架构 1 互联网应用架构发展 那些迫使 ...
- 【转】 Pro Android学习笔记(七十):HTTP服务(4):SOAP/JSON/XML、异常
目录(?)[-] SOAP JSON和XMLPullParser Exception处理 文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注册等附加条件,转载须注明出处:http://blog. ...
- 【转】 Pro Android学习笔记(六八):HTTP服务(2):HTTP POST
目录(?)[-] 找一个测试网站 HTTP POST小例子 上次学习了HTTP GET请求,这次学习一下HTTP POST. 找一个测试网站 小例子好写,但要找个测试网站就有些麻烦,一下子无从入手,都 ...
- Orleans[NET Core 3.1] 学习笔记(三)( 3 )服务端配置
服务端配置 Silo通过SiloHostBuilder和许多补充选项类以编程方式进行配置. Silo配置有几个关键方面: Orleans集群信息 集群提供程序(不知道咋翻译) Silo到Silo和Cl ...
- 硬件访问服务学习笔记_WDS
1.Android驱动框架App1 App2 App3 App4-------------------硬件访问服务-------------------JNI-------------------C库 ...
随机推荐
- CF #261 div2 D. Pashmak and Parmida's problem (树状数组版)
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants he ...
- golang matrix
package main import ( "fmt" "go.matrix-go1" //比较有名的关于Matrix在golang中的方法库 "st ...
- JS/CSS 响应式样式实例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- 【习题 6-10 UVA - 246】10-20-30
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 发牌的那个牌堆用一个deque,7个牌堆用vector来模拟. 然后按照题意模拟就好. 不难. [代码] /* 1.Shoud it ...
- JSP中的EL表达式详细介绍
一.JSP EL语言定义 EL 提供了在 JSP 脚本编制元素范围外使用运行时表达式的功能.脚本编制元素是指页面中能够用于在 JSP 文件中嵌入 Java 代码的元素.它们通常用于对象操作以及执行那些 ...
- Javascript和jquery事件--鼠标滚轮事件WheelEvent
<1>js事件 滚轮事件在js中,不同浏览器还是有不同的,介于我只测试谷歌和火狐浏览器的情况,其他浏览器有待自行探索.有三种写法: target.onmousewheel = wheel; ...
- 关于mysql事务行锁for update实现写锁的功能
关于mysql事务行锁for update实现写锁的功能 读后感:用切面编程的理论来讲,数据库的锁对于业务来说是透明的.spring的事务管理代码,业务逻辑代码,表锁,应该是三个不同的设计层面. 在电 ...
- Python内部机制-PyObject对象
PyObject对象机制的基石 学过Python的人应该非常清晰,Python中一切都是对象,全部的对象都有一个共同的基类,对于本篇博文来说,一切皆是对象则是探索Python的对象机制的一个入口点.我 ...
- volatile关键字深入理解
前言: 这个关键字的重点就三个字,就是可见性.但是面试的时候,你说出可见性三个字,基本上满分100的话,最多只能得到20分.剩下的那80分,就要靠你用硬功夫去获得了. 所谓的硬功夫,其实就是要整明白, ...
- RabbitMQ安全相关的网络资源介绍
无法用guest远程訪问RabbitMQ的的解决方式 Can't access RabbitMQ web management interface after fresh install http:/ ...