Python写的微服务如何融入Spring Cloud体系?
<p><strong><span style="font-size: 16px; color: rgba(0, 0, 0, 1)"><span style="font-size: 17px">前言</span></span></strong></p><p><span style="font-size: 16px">在今天的文章中小码哥将会给大家分享一个目前工作中遇到的一个比较有趣的案例,就是<strong>如何将Python写的微服务融入到以Java技术栈为主的Spring Cloud微服务体系中</strong>?也许有朋友会有疑问,到底什么样的场景需要用Python写一个微服务,并且还要融入以Java技术栈为主的Spring Cloud微服务体系中呢?</span></p>
<p> </p>
<p> </p>
<p style="line-height: 2em; margin-top: 5px"><span style="font-size: 16px">大致情况是这样的,小码哥目前所在的公司后端技术栈基本上是以Java为主,并且整个后端软件系统采用的也是基于Spring Cloud框架为主的微服务架构(<em><span style="font-size: 15px; color: rgba(122, 68, 66, 1)">PS:在以往的文章中小码哥写了一些关于这方面的文章,大家可以在文末的推荐阅读中查看相关内容</span></em><span style="font-size: 16px">),服务的注册发现是基于<strong>Consul</strong>,而服务的调用及负载均衡也都是基于<strong>FeignClient</strong>调用以及<strong>Robbin</strong>客户端依赖来实现的,所以整体架构大概就是这样的一个标准Spring Cloud微服务架构。如图所示:</span></span></p>
<p style="line-height: 2em; margin-top: 5px"> </p>
<p style="line-height: 2em; margin-top: 5px"><span style="font-size: 16px"><img src="https://img2018.cnblogs.com/blog/1571688/201905/1571688-20190529143829589-861768682.png"></span></p>
<p style="text-align: left; line-height: 2em"> </p>
<p style="text-align: left; line-height: 2em"><span style="font-size: 16px">大部分场景下<strong>基于以上微服务架构是比较好扩展的</strong>,例如你有一个新的微服务,如果完全可以通过Java语言构建的话,那就是非常简单的一件事,因为你只需要基于Spring Boot编写一个微服务项目,然后通过Spring Cloud提供的注解将其快速地注入Consul的服务注册&发现机制,然后就可以很快地对内或对外提供服务了。</span></p>
<p style="text-align: left; line-height: 2em"> </p>
<p style="text-align: left; line-height: 2em"><span style="font-size: 16px">而在这里,小码哥遇到的是一个比较特殊的场景,因为最近小码哥一直在做一些出行行业相关的事情,所以需要做一些<strong>路径规划和计算</strong>的工作。这里就有一个比较棘手的需求:“<strong>需要对车辆的调度做一些路径规划,简单的来说就是地图上有很多个坐标点的位置,需要给有限的运营车辆做路径规划,尽量以一个距离最短的最佳路线去遍历完这些位置,从而节省运营资源提高运营效率”</strong>。</span></p>
<p style="text-align: left; line-height: 2em"><span style="font-size: 16px"> </span></p>
<p style="text-align: left; line-height: 2em"><span style="font-size: 16px">关于这个问题,实际上是涉及到计算机科学中比较经典的一个<strong><span style="font-size: 16px">TSP(旅行商)算法</span></strong>问题,如果大家对这个算法有了解的话,就会理解这个问题需要非常大的计算量,因为每多几个位置,其算法的复杂度就会呈指数增长。而要解决这个问题,如果自行编写解决方案的话需要耗费很大的精力并且还需要不断的优化算法!</span></p>
<p style="text-align: left; line-height: 2em"><span style="font-size: 16px"> </span></p>
<p style="text-align: left; line-height: 2em"><span style="font-size: 16px">所以这个时候小码哥就想是不是有一些相对比较可靠的开源工具可以利用呢?所以经过一些研究和调研,果然发现有一个<strong>Google开源的运筹计算工具<em>OR-TOOLS</em></strong>,其中提供了关于<strong>TSP及VRP问题</strong>的解法,关于这个工具解决TSP及VRP问题的方法与TSP问题一样,小码哥会在后面找机会给大家分享。</span></p>
<p style="text-align: left; line-height: 2em"> </p>
<p style="text-align: left; line-height: 2em"><span style="font-size: 16px">因为<strong>计算量非常大</strong>所以在使用OR-TOOLS工具时,我们需要在本地安装OR-TOOLS软件,而在具体编写计算代码时因其对Java的支持体验比较差(<strong>缺乏官方发布的Maven依赖,以及示例代码不全等</strong>),所以最终我们<strong>需要使用Python语言来进行开发,并且每一次的路径规划计算,都需要以服务的方式对上层应用进行开放。</strong></span></p>
<p style="text-align: left; line-height: 2em"> </p>
<p style="text-align: left; line-height: 2em"><span style="font-size: 16px">说到这里,各位应该已经理解了小码哥的纠结的问题了,因为<strong>Python服务相对于Spring Cloud这一套体系来说,算是一个异构服务了</strong>,其本身并不像Java那样可以很方便的利用<strong>Spring Boot、Spring Cloud</strong>提供的一套成熟的体系。而如果选择<strong>不融入Spring Cloud体系</strong>,那意味着对于Python服务,我们<strong>需要做单独的部署及负载设计</strong>。例如,我们可能需要单独部署几个Python节点,然后通过Nginx单独配置负载均衡,内部微服务调用也需要每次都绕到Nginx那一层才可以以负载的方式访问。如下图所示:</span></p>
<p style="text-align: left; line-height: 2em"> </p>
<p style="text-align: left; line-height: 2em"><span style="font-size: 16px"><img src="https://img2018.cnblogs.com/blog/1571688/201905/1571688-20190529143905578-735716480.png"></span></p>
<p> </p>
<p><span style="font-size: 16px">实际上这种方式就是回到了早期<strong>传统服务架构时代的负载均衡模式配置方式</strong>上去了,虽然也没有太大的问题,只是为这样<strong>个别的异构服务单独设置一套部署体系,从成本及扩展性上来说的确有些别扭</strong>!所以,如果我们可以直接将Python写的异构服务也能通过注册到Consul的话,这样也就融入了标准的Spring Cloud微服务体系,问题就简单多了!</span></p>
<p> </p>
<p><strong><span style="font-size: 16px; color: rgba(0, 0, 0, 1)"><span style="font-size: 17px">构建Python web服务</span></span></strong></p>
<p> </p>
<p> </p>
<p style="line-height: 2em"><span style="font-size: 16px">接下来我们就以具体代码的方式先一起来看看怎么样<strong>编写一个Python web服务</strong>,并看看怎么样才可以将其注册到<strong>Consul</strong>中,并与其他微服务实现服务发现和调用!在基于Python编写Web服务时,为了简化开发可以<strong>选择一个比较成熟的PythonWeb框架</strong>,这里小码哥用的是Tornado,Python中其他Web框架还有<strong>Flask、Django</strong>等,因为<strong>Tornado</strong>性能相对比较高适合做后端接口服务,所以就选择了<strong>Tornado</strong>,这里就不再进一步说明了。</span></p>
<p> </p>
<p> </p>
<p> </p>
<p style="line-height: 2em"><span style="font-size: 16px">在具体进行代码开发时,我们需要安装好Python开发环境,这里小码哥使用的是<strong>Python3.7.3</strong>,而T<strong>ornado使用的则是5.1.1版本</strong>,具体的安装方式大家可以查一下,这里就不再多说!接下了,我们具体来看下在真实的项目工程中时怎么将Python注入Consul的!</span></p>
<p> </p>
<p> </p>
<p> </p>
<p style="line-height: 2em"><span style="font-size: 16px"><span style="font-size: 16px; letter-spacing: normal">因为Python不像Java那样<strong>基于Spring Cloud有一套完整的依赖包</strong>,可以很方便地使用一个注解就可以进行服务注册与发现,所以我们需要<strong><span style="font-size: 16px; letter-spacing: normal">基于consulate这个Python库来单独编写服务注册代码</span></strong>,如下:</span></span></p>
<p style="line-height: 2em"> </p>
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">import json
from random import randint
from consulate import Consul
# consul 操作类
import requests
class ConsulClient():
def __init__(self, host=None, port=None, token=None):# 初始化,指定consul主机,端口,和token
self.host = host# consul 主机
self.port = port# consul 端口
self.token = token
self.consul = Consul(host=host, port=port)
def register(self, name, service_id, address, port, tags, interval, httpcheck):# 注册服务 注册服务的服务名端口以及 健康监测端口
self.consul.agent.service.register(name, service_id=service_id, address=address, port=port, tags=tags,
interval=interval, httpcheck=httpcheck)
def deregister(self, service_id):
# 此处有坑,源代码用的get方法是不对的,改成put,两个方法都得改
self.consul.agent.service.deregister(service_id)
self.consul.agent.check.deregister(service_id)
def getService(self, name):# 负载均衡获取服务实例
url = 'http://' + self.host + ':' + str(self.port) + '/v1/catalog/service/' + name# 获取 相应服务下的DataCenter
dataCenterResp = requests.get(url)
if dataCenterResp.status_code != 200:
raise Exception('can not connect to consul ')
listData = json.loads(dataCenterResp.text)
dcset = set()# DataCenter 集合 初始化
for service in listData:
dcset.add(service.get('Datacenter'))
serviceList = []# 服务列表 初始化
for dc in dcset:
if self.token:
url = 'http://' + self.host + ':' + self.port + '/v1/health/service/' + name + '?dc=' + dc + '&token=' + self.token
else:
url = 'http://' + self.host + ':' + self.port + '/v1/health/service/' + name + '?dc=' + dc + '&token='
resp = requests.get(url)
if resp.status_code != 200:
raise Exception('can not connect to consul ')
text = resp.text
serviceListData = json.loads(text)
for serv in serviceListData:
status = serv.get('Checks').get('Status')
if status == 'passing':# 选取成功的节点
address = serv.get('Service').get('Address')
port = serv.get('Service').get('Port')
serviceList.append({'port': port, 'address': address})
if len(serviceList) == 0:
raise Exception('no serveice can be used')
else:
service = serviceList# 随机获取一个可用的服务实例
return service['address'], int(service['port'])
def getServices(self):
return self.consul.agent.services()
</pre>
</div>
<p style="line-height: 2em"> </p>
<p> </p>
<p style="font-size: 16px; color: rgba(62, 62, 62, 1); word-spacing: 0; letter-spacing: 0; font-family: "Helvetica Neue", Helvetica, "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif; line-height: 2em"><span style="font-size: 16px">有了以上这段服务注册代码的实现,我们再来看看<strong>入口代码中如何在启动服务时注入Consul</strong>,代码如下:</span></p>
<p style="font-size: 16px; color: rgba(62, 62, 62, 1); word-spacing: 0; letter-spacing: 0; font-family: "Helvetica Neue", Helvetica, "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif; line-height: 2em"> </p>
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">import os
import sys
from importlib import reload
import tornado.web
from tornado.ioloop import IOLoop
from tornado.options import define, options, parse_command_line
from apps.handlers.VehicleRoutingHandler import VehicleRoutingHandler
from apps.handlers.HealthChecker import HealthChecker
from utils.consul_client import ConsulClient
reload(sys)
def main():
# 读取项目配置
from conf.config import getConfig
conf = getConfig()
c = ConsulClient(conf.consul_address, conf.consul_port)
service_id = conf.application_name + ":" + conf.ip + ':' + str(conf.server_port)
# print(c.consul.agent.services())
name = conf.application_name
address = conf.ip
port = conf.server_port
tags =
interval = 5
httpcheck = conf.consul_healthCheckPath
c.register(name, service_id, address, port, tags, interval, httpcheck)
parse_command_line()
app = tornado.web.Application(
[
(r"/routing/vehiclePathPlan?", VehicleRoutingHandler),
(r"/actuator/health", HealthChecker)
],
cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(conf.server_port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()
</pre>
</div>
<p style="font-size: 16px; color: rgba(62, 62, 62, 1); word-spacing: 0; letter-spacing: 0; font-family: "Helvetica Neue", Helvetica, "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif; line-height: 2em"> </p>
<p> </p>
<p><span style="font-size: 16px">可以看到上述代码通过<strong>配置获取了consul的地址及端口信息,并自定义了服务节点的serviceId、tags</strong>以及进行健康性检查时,<strong>Consul探测的服务接口地址</strong>的定义:</span></p>
<p> </p>
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">/actuator/health
</pre>
</div>
<p> </p>
<p> </p>
<p><span style="font-size: 16px">我们知道<strong>Consul与微服务之间需要通过健康性检查来做心跳</strong>,在Java中因为Spring Cloud依赖包已经替我们实现好了这样的接口,而<strong>在Python中就需要我们手工定义,如上述代码中我们就定义了/actuator/health服务</strong>,并实现了其处理代码,很简单就是返回成功,如下:</span></p>
<p> </p>
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">import tornado.web
class HealthChecker(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.write("ok")
</pre>
</div>
<p> </p>
<p> </p>
<p style="line-height: 2em"><span style="font-size: 16px">这样在<strong>服务注册到Consul之后</strong><strong>,Consul就可以通过这个接口来与Python微服务之间通过发送心跳来探活了</strong>。此时,如果我们在配置中制定Consul的地址,并启动Python微服务,就可以将其注入Consul了,如:</span></p>
<p style="line-height: 2em"><span style="font-size: 16px"> </span></p>
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">MacBook-Pro-2:routing guanliyuan$ python3 manage.py dev
['manage.py', 'dev']
dev
200 GET /actuator/health (127.0.0.1) 1.38ms
200 GET /actuator/health (127.0.0.1) 0.76ms
200 GET /actuator/health (127.0.0.1) 0.58ms
200 GET /actuator/health (127.0.0.1) 0.57ms
</pre>
</div>
<p> </p>
<p><span style="font-size: 16px">启动服务后,就<strong>可以看到Consul发过来的心跳请求了</strong>,此时如果我们打开Consul的web控制台,也能看到服务成功的被注册到Consul上了,如:</span></p>
<p><span style="font-size: 16px"><img src="https://img2018.cnblogs.com/blog/1571688/201905/1571688-20190529144325783-611818160.png"></span></p>
<p> </p>
<p> <span style="font-size: 16px">之后该<strong>Python服务就可以像其他Java编写的微服务一样</strong>即可以通过api-gateway直接被前端调用,也可以<strong>通过FeignClient以负载均衡的方式被其他微服务调用</strong>了!</span></p>
<p> </p>
<p><strong><span style="font-size: 16px; color: rgba(0, 0, 0, 1)"><span style="font-size: 17px">Python 多环境配置</span></span></strong></p>
<p> </p>
<p><span style="font-size: 16px">这里再多给大家分享一点,就是我们知道在Spring Cloud微服务中,我们可以通过<strong>spring.profile.active这个参数来指定不同环境的配置</strong>,从而实现多环境适配,而<strong>在Python中因为没有像Spring Boot这样的框架</strong>,所以我们只能自己来实现了,例如,下面的配置代码就是给Python微服务实现的一个多环境配置的代码,如下:</span></p>
<p> </p>
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">import os
import socket
import manage
class Config(object):# 默认配置
DEBUG = False
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
application_name = "routing"
application_version = "1.0"
server_port = 9090
# get attribute
def __getitem__(self, key):
return self.__getattribute__(key)
class DevelopmentConfig(Config):# 开发环境
consul_address = "127.0.0.1"
consul_port = "8500"
consul_healthCheckPath = "http://127.0.0.1:9090/actuator/health"
consul_tags = "dev"
class ProductionConfig(Config):# 生产环境
consul_address = "127.0.0.1"
consul_port = "8500"
consul_healthCheckPath = "http://127.0.0.1:9090/actuator/health"
consul_tags = "prod"
# 环境映射关系
mapping = {
'dev': DevelopmentConfig,
'pro': ProductionConfig,
'default': DevelopmentConfig
}
# 根据脚本参数,来决定用那个环境配置
import sys
def getConfig():
print(sys.argv)
num = len(sys.argv) - 1# 参数个数
if num < 1 or num > 1:
exit("参数错误,必须传环境变量!比如: python xx.py dev|pro|default")
env = "dev"# sys.argv# 环境
print(env)
APP_ENV = os.environ.get('APP_ENV', env).lower()
return mapping()# 实例化对应的环境
</pre>
</div>
<p> </p>
<p> </p>
<p><span style="font-size: 16px">这样我们在<strong>启动python脚本时只需要传递对应的环境参数,也可以实现多环境的配置读取了</strong>,例如:</span></p>
<p> </p>
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">MacBook-Pro-2:routing guanliyuan$ python3 manage.py dev
['manage.py', 'dev']
dev
</pre>
</div>
<p> </p>
<p> </p>
<p><strong><span style="font-size: 17px; color: rgba(0, 0, 0, 1)">后记</span></strong></p>
<p> </p>
<p><span style="font-size: 16px">以上就是关于<strong>Python微服务作为异构服务融入Spring Cloud体系</strong>的一些介绍了,在实际的场景中还会有诸如其他语言编写的微服务的场景,如Go!其基本思路类似,只是Java相对于其他语言来说,由于其完整的开源生态,会简单很多!</span></p>
<p style="text-align: left"> </p>
<p style="text-align: left"> </p>
<p style="box-sizing: border-box; margin-top: 15px; margin-bottom: 15px; font-size: 16px; white-space: pre-line; line-height: 30px; color: rgba(74, 74, 74, 1); font-family: Avenir, -apple-system-font, 微软雅黑, sans-serif; text-align: left"><strong style="max-width: 100%; font-size: 16px; letter-spacing: 0.544px; text-align: center; white-space: normal; box-sizing: border-box !important; overflow-wrap: break-word !important">推荐阅读:</strong></p>
<p style="text-align: left"> </p>
<p style="box-sizing: border-box; margin-top: 15px; margin-bottom: 15px; font-size: 16px; white-space: pre-line; line-height: 30px; color: rgba(74, 74, 74, 1); font-family: Avenir, -apple-system-font, 微软雅黑, sans-serif; text-align: left"><span style="font-size: 14px; text-decoration: underline">Spring Cloud微服务接口这么多怎么调试?</span></p>
<p style="text-align: left"> </p>
<p style="box-sizing: border-box; margin-top: 15px; margin-bottom: 15px; font-size: 16px; white-space: pre-line; color: rgba(74, 74, 74, 1); font-family: Avenir, -apple-system-font, 微软雅黑, sans-serif; line-height: normal; text-align: left"><span style="font-size: 14px; text-decoration: underline">Spring Boot集成Flyway实现数据库版本控制?<br></span></p>
<p style="text-align: left"> </p>
<p style="box-sizing: border-box; margin-top: 15px; margin-bottom: 15px; font-size: 16px; white-space: pre-line; color: rgba(74, 74, 74, 1); font-family: Avenir, -apple-system-font, 微软雅黑, sans-serif; line-height: normal; text-align: left"><span style="font-size: 14px">Spring Cloud微服务如何实现熔断降级?</span></p>
<p style="text-align: left"> </p>
<p style="box-sizing: border-box; margin-top: 15px; margin-bottom: 15px; font-size: 16px; white-space: pre-line; color: rgba(74, 74, 74, 1); font-family: Avenir, -apple-system-font, 微软雅黑, sans-serif; line-height: normal; text-align: left"><span style="font-size: 14px">Spring Cloud微服务如何设计异常处理机制?</span></p>
<p style="text-align: left"> </p>
<p style="box-sizing: border-box; margin-top: 15px; margin-bottom: 15px; font-size: 16px; white-space: pre-line; color: rgba(74, 74, 74, 1); font-family: Avenir, -apple-system-font, 微软雅黑, sans-serif; line-height: normal; text-align: left"><span style="font-size: 14px">Spring Cloud微服务中网关服务是如何实现的?(Zuul篇)</span></p>
<p style="text-align: left"> </p>
<p style="box-sizing: border-box; margin-top: 15px; margin-bottom: 15px; font-size: 16px; white-space: pre-line; color: rgba(74, 74, 74, 1); font-family: Avenir, -apple-system-font, 微软雅黑, sans-serif; line-height: normal; text-align: left"><span style="font-size: 14px">Spring Cloud是怎么运行的?</span></p>
<p style="text-align: left"> </p>
<p style="box-sizing: border-box; margin-top: 15px; margin-bottom: 15px; font-size: 16px; white-space: pre-line; color: rgba(74, 74, 74, 1); font-family: Avenir, -apple-system-font, 微软雅黑, sans-serif; line-height: normal; text-align: left"><span style="font-size: 14px">基于SpringCloud的微服务架构演变史?</span></p>
<p style="text-align: left"> </p>
<p style="box-sizing: border-box; margin-top: 15px; margin-bottom: 15px; font-size: 16px; white-space: pre-line; color: rgba(74, 74, 74, 1); font-family: Avenir, -apple-system-font, 微软雅黑, sans-serif; line-height: normal; text-align: left"><span style="font-size: 14px; text-decoration: underline">Spring Boot到底是怎么运行的,你知道吗?</span></p>
<p style="box-sizing: border-box; margin-top: 15px; margin-bottom: 15px; font-size: 16px; white-space: pre-line; color: rgba(74, 74, 74, 1); font-family: Avenir, -apple-system-font, 微软雅黑, sans-serif; line-height: normal; text-align: left"> </p><br><br>
来源:https://www.cnblogs.com/wudimanong/p/10943825.html
頁:
[1]