欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

windows环境下如何搭建Consul+Ocelot

程序员文章站 2023-10-20 23:12:48
下面的是markdown格式的文档,懒得排版了,有兴趣的话可以去github上看,有源码 Github:https://github.com/yuchengao0721/Consul-Ocelot.git #
Consul+Ocelot的服务网关与注册等功能的实现
......

下面的是markdown格式的文档,懒得排版了,有兴趣的话可以去github上看,有源码

github:https://github.com/yuchengao0721/consul-ocelot.git

# <center>consul+ocelot的服务网关与注册等功能的实现</center>
此文档主要提供给开发人员使用,
暂时仅实现服务注册、服务发现、负载均衡等功能,
更多功能需配合官方文档或第三方文档进行更细致化开发。

###`有兴趣可以了解一下`

* #### consul相关:

* [consul官网](https://www.consul.io/)
* [consul简介](https://blog.51cto.com/firephoenix/2131616)
* [consul使用手册](https://blog.csdn.net/liuzhuchen/article/details/81913562)
* [consul配置手册](https://www.cnblogs.com/sunsky303/p/9209024.html)

* #### ocelot相关:

* [ocelot官网](https://ocelot.readthedocs.io/en/latest/)
* [ocelot简介](https://blog.csdn.net/qin_yu_2010/article/details/82323003)

## 1. windows环境的搭建

在windows环境下搭建consul进行服务注册、服务网关等
此次环境配置:
server
ip:192.168.199.203
windows版本:ws 2012 r2 standard
处理器:i5-4570
内存:8g
系统类型:x64
client
ip:192.168.199.40
windows版本:w10企业版
处理器:i7-3720qm
内存:8g
系统类型:x64

### 1.1 服务器环境搭建

* #### 1.1.1 consul_server端
* ##### step1
前往consul官网[下载](https://www.consul.io/downloads.html) windows版本的consul安装程序

* ##### step2
将下好的软件复制到一个新建好的文件夹a,在文件夹a内部新建server.json文件,写入内容
```javascript
{
"datacenter": "dc1",
"data_dir": "opt/consul/data",
"node_name": "consul-server01",//你的consul服务的别名
"server": true,
"bootstrap_expect": 1,
"bind_addr": "192.168.199.203",//你服务器的ip或者外网域名
"client_addr": "0.0.0.1",//此处固定写法,方便其他机器查看你的consului
"ui":true
}
```

* ##### step3
在文件夹a内部新建runconsul.bat文件,写入内容
'''
consul agent -config-dir server.json
pause
'''

* ##### step4
运行runconsul.bat文件,出现下列内容即为开启成功
![](windowsserverstep4.jpg)
在服务器上打开浏览器输入127.0.0.1:8500,可以查看consul运行情况,

 

* #### 1.1.2 consul_client端
* ##### step1
前往consul官网[下载](https://www.consul.io/downloads.html) windows版本的consul安装程序

* ##### step2
将下好的软件复制到一个新建好的文件夹a,在文件夹a内部新建server.json文件,写入内容
```javascript
{
"datacenter": "dc1",
"data_dir": "opt/consul/data",
"node_name": "ych-client",//你的client的别名(仅支持全字母、数字、破折号)
"server": false,//是否是server
"bind_addr": "192.168.199.40",//当前服务器ip或者域名
"client_addr": "192.168.199.40",//可以写当前服务器的ip,也可以写0.0.0.0,主要区别是是否可以在本机查看ui
"ui":true,//是否开启ui
"retry_join": ["192.168.199.203"],//重新加入的server服务器的ip,可为多个,直到成功
"retry_interval": "30s",//失败重连间隔
"rejoin_after_leave": true,
"start_join":["192.168.199.203"]//第一次加入的server服务器的ip,可为多个,直到成功
}
```

* ##### step3
在文件夹a内部新建runconsul.bat文件,写入内容
'''
consul agent -config-dir server.json
pause
'''

* ##### step4
运行runconsul.bat文件,出现下列内容即为开启成功
![](windowsclientstep4.jpg)
在server服务器上打开浏览器输入127.0.0.1:8500,可以查看node加入新节点。

### 1.2 api注册
* ##### step1
引入下列两个nuget包
```javascript
<packagereference include="microsoft.aspnetcore.http.features" version="2.2.0" />
<packagereference include="microsoft.aspnetcore.razor.design" version="2.2.0" privateassets="all" />
```

* ##### step2

添加公司nuget上的consulregister引用

在program添加下列代码:
```javascript
public static iwebhostbuilder createwebhostbuilder(string[] args) =>
webhost.createdefaultbuilder(args)
.usekestrel()
.usecontentroot(directory.getcurrentdirectory())
.useiis()
.usestartup<startup>();
```
在startup添加下列代码:
```javascript
public void configureservices(iservicecollection services)
{
services.addconsul(configuration);//注册consul中间件
services.addmvc().setcompatibilityversion(compatibilityversion.version_2_2);
}
public void configure(iapplicationbuilder app, ihostingenvironment env)
{
if (env.isdevelopment())
{
app.usedeveloperexceptionpage();
}
else
{
app.usehsts();
}
app.usecors();
app.usehttpsredirection();
app.useconsul();//使用consul中间件
app.usemvc();
}
```
* ##### step3
在appsettings.json内添加下列内容
```javascript
"host": "http://192.168.199.40:8041",//当前api的ip或者域名
"servicediscovery": {
"servicename": "api_1",//注册的api名称,用以进行服务查找,以及负载均衡
"consul": {
"httpendpoint": "http://192.168.199.40:8500"//api需要注册的client地址(端口未固定8500,或者可映射为8500的端口)
}
}
```

* ##### step4
运行程序然后打开server的consului即可查看注册了该api

 

### 1.3 ocelot进行服务网关搭建和服务发现
这个程序建议部署在consul-server服务器上

* ##### step1
新建一个webapi core项目

引入下列两个nuget包
```javascript
<packagereference include="ocelot" version="13.5.2" />
<packagereference include="ocelot.provider.consul" version="13.5.2" />
```

 

* ##### step2(重要)
此处为配置项,暂时需要手动实现

根目录下新建ocelot.json文件,写入内容
```javascript
{
"reroutes": [
{
"useservicediscovery": true,
"downstreampathtemplate": "/{url}",//下游路由规则
"downstreamscheme": "http",//请求协议
"servicename": "api_1",//对应的服务名称
"loadbalanceroptions": {
"type": "roundrobin"//负载均衡规则:轮询
},
"upstreampathtemplate": "/client1/{url}",//上游路由规则不可重复,否则上游无法寻址到正确的下游路由
"upstreamhttpmethod": [ "get", "post" ],//允许的请求方法
"reroutescasesensitive": false
},
{
"useservicediscovery": true,
"downstreampathtemplate": "/{url}",
"downstreamscheme": "http",
"servicename": "api_2",
"loadbalanceroptions": {
"type": "roundrobin"
},
"upstreampathtemplate": "/client2/{url}",
"upstreamhttpmethod": [ "get", "post" ],
"reroutescasesensitive": false
}
],
"globalconfiguration": {
// 使用consul服务治理
"servicediscoveryprovider": {
"host": "192.168.199.203",//想要发现的server服务ip
"port": 8500,//固定端口或者可映射到该端口的映射端口
"pollinginterval": 100, //健康检查时间间隔ms
"type": "consul",
"token": null,
"configurationkey": null
}
}
}
```
在program添加下列代码:
```javascript
public static iwebhostbuilder createwebhostbuilder(string[] args) =>
webhost.createdefaultbuilder(args)
.configureappconfiguration((hostingcontext, config) =>
{
config
.setbasepath(hostingcontext.hostingenvironment.contentrootpath)
.addjsonfile("appsettings.json", true, true)
.addjsonfile($"appsettings.{hostingcontext.hostingenvironment.environmentname}.json", true, true)
.addjsonfile("ocelot.json")
.addenvironmentvariables();
})
.usestartup<startup>();
```
在startup添加下列代码:
```javascript
public void configureservices(iservicecollection services)
{
//添加ocelot中间件
services.addocelot(
new configurationbuilder()
.addjsonfile("ocelot.json", optional: false, reloadonchange: true).build())
.addconsul()
.addconfigstoredinconsul();
}

public void configure(iapplicationbuilder app, ihostingenvironment env)
{
if (env.isdevelopment())
{
app.usedeveloperexceptionpage();
}
else
{
app.usehsts();
}
//添加程序健康启动检查
app.map("/healthcheck", s =>
{
s.run(async context =>
{
await context.response.writeasync("ok");
});
});
app.useocelot().wait();//使用ocelot中间件
}
```
* ##### step3
运行程序即可


### 1.3 小结
至此windows环境下的服务网关与服务发现雏形已经搭建好,
下面是一些可能遇到的问题
####1.3.1 问题?s
#####q:遇到服务器积极拒绝怎么解决?
a:检查8500端口是否已经开放,[具体做法](https://jingyan.baidu.com/article/37bce2be40cf921002f3a229.html);如果端口以开放仍有问题,关闭防火墙。