Python写的微服务如何融入Spring Cloud体系?

2022-12-07,,,,

前言

在今天的文章中小码哥将会给大家分享一个目前工作中遇到的一个比较有趣的案例,就是如何将Python写的微服融入到以Java技术栈为主的Spring Cloud微服务体系?也许有朋友会有疑问,到底什么样的场景需要用Python写一个微服务,并且还要融入以Java技术栈为主的Spring Cloud微服务体系中呢?

大致情况是这样的,小码哥目前所在的公司后端技术栈基本上是以Java为主,并且整个后端软件系统采用的也是基于Spring Cloud框架为主的微服务架构(PS:在以往的文章中小码哥写了一些关于这方面的文章,大家可以在文末的推荐阅读中查看相关内容),服务的注册发现是基于Consul,而服务的调用及负载均衡也都是基于FeignClient调用以及Robbin客户端依赖来实现的,所以整体架构大概就是这样的一个标准Spring Cloud微服务架构。如图所示:

大部分场景下基于以上微服务架构是比较好扩展的,例如你有一个新的微服务,如果完全可以通过Java语言构建的话,那就是非常简单的一件事,因为你只需要基于Spring Boot编写一个微服务项目,然后通过Spring Cloud提供的注解将其快速地注入Consul的服务注册&发现机制,然后就可以很快地对内或对外提供服务了。

而在这里,小码哥遇到的是一个比较特殊的场景,因为最近小码哥一直在做一些出行行业相关的事情,所以需要做一些路径规划和计算的工作。这里就有一个比较棘手的需求:“需要对车辆的调度做一些路径规划,简单的来说就是地图上有很多个坐标点的位置,需要给有限的运营车辆做路径规划,尽量以一个距离最短的最佳路线去遍历完这些位置,从而节省运营资源提高运营效率”

关于这个问题,实际上是涉及到计算机科学中比较经典的一个TSP(旅行商)算法问题,如果大家对这个算法有了解的话,就会理解这个问题需要非常大的计算量,因为每多几个位置,其算法的复杂度就会呈指数增长。而要解决这个问题,如果自行编写解决方案的话需要耗费很大的精力并且还需要不断的优化算法!

所以这个时候小码哥就想是不是有一些相对比较可靠的开源工具可以利用呢?所以经过一些研究和调研,果然发现有一个Google开源的运筹计算工具OR-TOOLS,其中提供了关于TSP及VRP问题的解法,关于这个工具解决TSP及VRP问题的方法与TSP问题一样,小码哥会在后面找机会给大家分享。

因为计算量非常大所以在使用OR-TOOLS工具时,我们需要在本地安装OR-TOOLS软件,而在具体编写计算代码时因其对Java的支持体验比较差(缺乏官方发布的Maven依赖,以及示例代码不全等),所以最终我们需要使用Python语言来进行开发,并且每一次的路径规划计算,都需要以服务的方式对上层应用进行开放。

说到这里,各位应该已经理解了小码哥的纠结的问题了,因为Python服务相对于Spring Cloud这一套体系来说,算是一个异构服务了,其本身并不像Java那样可以很方便的利用Spring Boot、Spring Cloud提供的一套成熟的体系。而如果选择不融入Spring Cloud体系,那意味着对于Python服务,我们需要做单独的部署及负载设计。例如,我们可能需要单独部署几个Python节点,然后通过Nginx单独配置负载均衡,内部微服务调用也需要每次都绕到Nginx那一层才可以以负载的方式访问。如下图所示:

实际上这种方式就是回到了早期传统服务架构时代的负载均衡模式配置方式上去了,虽然也没有太大的问题,只是为这样个别的异构服务单独设置一套部署体系,从成本及扩展性上来说的确有些别扭!所以,如果我们可以直接将Python写的异构服务也能通过注册到Consul的话,这样也就融入了标准的Spring Cloud微服务体系,问题就简单多了!

构建Python web服务

接下来我们就以具体代码的方式先一起来看看怎么样编写一个Python web服务,并看看怎么样才可以将其注册到Consul中,并与其他微服务实现服务发现和调用!在基于Python编写Web服务时,为了简化开发可以选择一个比较成熟的PythonWeb框架,这里小码哥用的是Tornado,Python中其他Web框架还有Flask、Django等,因为Tornado性能相对比较高适合做后端接口服务,所以就选择了Tornado,这里就不再进一步说明了。

在具体进行代码开发时,我们需要安装好Python开发环境,这里小码哥使用的是Python3.7.3,而Tornado使用的则是5.1.1版本,具体的安装方式大家可以查一下,这里就不再多说!接下了,我们具体来看下在真实的项目工程中时怎么将Python注入Consul的!

因为Python不像Java那样基于Spring Cloud有一套完整的依赖包,可以很方便地使用一个注解就可以进行服务注册与发现,所以我们需要基于consulate这个Python库来单独编写服务注册代码,如下:

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')[1].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[randint(0, len(serviceList) - 1)] # 随机获取一个可用的服务实例
return service['address'], int(service['port']) def getServices(self):
return self.consul.agent.services()

有了以上这段服务注册代码的实现,我们再来看看入口代码中如何在启动服务时注入Consul,代码如下:

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 = [conf.consul_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()

可以看到上述代码通过配置获取了consul的地址及端口信息,并自定义了服务节点的serviceId、tags以及进行健康性检查时,Consul探测的服务接口地址的定义:

/actuator/health

我们知道Consul与微服务之间需要通过健康性检查来做心跳,在Java中因为Spring Cloud依赖包已经替我们实现好了这样的接口,而在Python中就需要我们手工定义,如上述代码中我们就定义了/actuator/health服务,并实现了其处理代码,很简单就是返回成功,如下:

import tornado.web

class HealthChecker(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.write("ok")

这样在服务注册到Consul之后,Consul就可以通过这个接口来与Python微服务之间通过发送心跳来探活了。此时,如果我们在配置中制定Consul的地址,并启动Python微服务,就可以将其注入Consul了,如:

MacBook-Pro-2:routing guanliyuan$ python3 manage.py dev
['manage.py', 'dev']
dev
[I 190529 00:37:35 web:2162] 200 GET /actuator/health (127.0.0.1) 1.38ms
[I 190529 00:37:36 web:2162] 200 GET /actuator/health (127.0.0.1) 0.76ms
[I 190529 00:37:37 web:2162] 200 GET /actuator/health (127.0.0.1) 0.58ms
[I 190529 00:37:38 web:2162] 200 GET /actuator/health (127.0.0.1) 0.57ms

启动服务后,就可以看到Consul发过来的心跳请求了,此时如果我们打开Consul的web控制台,也能看到服务成功的被注册到Consul上了,如:

之后该Python服务就可以像其他Java编写的微服务一样即可以通过api-gateway直接被前端调用,也可以通过FeignClient以负载均衡的方式被其他微服务调用了!

Python 多环境配置

这里再多给大家分享一点,就是我们知道在Spring Cloud微服务中,我们可以通过spring.profile.active这个参数来指定不同环境的配置,从而实现多环境适配,而在Python中因为没有像Spring Boot这样的框架,所以我们只能自己来实现了,例如,下面的配置代码就是给Python微服务实现的一个多环境配置的代码,如下:

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[1] # 环境
print(env)
APP_ENV = os.environ.get('APP_ENV', env).lower()
return mapping[APP_ENV]() # 实例化对应的环境

这样我们在启动python脚本时只需要传递对应的环境参数,也可以实现多环境的配置读取了,例如:

MacBook-Pro-2:routing guanliyuan$ python3 manage.py dev
['manage.py', 'dev']
dev

后记

以上就是关于Python微服务作为异构服务融入Spring Cloud体系的一些介绍了,在实际的场景中还会有诸如其他语言编写的微服务的场景,如Go!其基本思路类似,只是Java相对于其他语言来说,由于其完整的开源生态,会简单很多!

推荐阅读:

Spring Cloud微服务接口这么多怎么调试?

Spring Boot集成Flyway实现数据库版本控制?

Spring Cloud微服务如何实现熔断降级?

Spring Cloud微服务如何设计异常处理机制?

Spring Cloud微服务中网关服务是如何实现的?(Zuul篇)

Spring Cloud是怎么运行的?

基于SpringCloud的微服务架构演变史?

Spring Boot到底是怎么运行的,你知道吗?

Python写的微服务如何融入Spring Cloud体系?的相关教程结束。

《Python写的微服务如何融入Spring Cloud体系?.doc》

下载本文的Word格式文档,以方便收藏与打印。