前言

该篇文章分享如何将Python Web服务融入到Spring Cloud微服务体系中,并调用其服务,Python Web框架用的是Flask

方案

Sidecar+ Flask,在这里,我们会使用Sidecar将Python接口注册到SpringCloud中,将Python接口当作Java接口进行调用(通过SpringCloud去调用Sidecar,然后通过Sidecar去转发我们的程序请求)

Sidecar是SpringCloud提供的一个可将第三方的rest接口集成到SpringCloud中的工具

Python服务

manage.py

import json

from flask import Flask, Response, request, make_response, jsonify

app = Flask(__name__)

@app.route("/health")

def health():

result = {'status': 'UP'}

return Response(json.dumps(result), mimetype='application/json')

@app.route("/getUser")

def getUser():

result = {'username': 'python', 'password': 'python'}

return Response(json.dumps(result), mimetype='application/json')

@app.errorhandler(404)

def not_found(error):

return make_response(jsonify({'error': 'Not found'}), 404)

if __name__ == "__main__":

app.run(host="0.0.0.0", port=3000)

大致说下上述代码,Python服务监听3000端口,health方法用于给Sidecar提供健康接口,用于实时向Sidecar提供自己的健康状态,getUser是Python向外界提供的服务

运行方式

python manage.py runserver

sidecar-server工程

添加依赖

org.springframework.cloud

spring-cloud-starter-eureka

org.springframework.cloud

spring-cloud-netflix-sidecar

org.springframework.boot

spring-boot-starter-test

test

SidecarApplication.java

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.netflix.sidecar.EnableSidecar;

@EnableSidecar

@SpringBootApplication

public class SidecarApplication {

public static void main(String[] args) {

SpringApplication.run(SidecarApplication.class, args);

}

}

application.yml

spring:

profiles:

active: "dev"

application:

name: demo-sidecar

sidecar:

port: 3000

health-uri: http://localhost:${sidecar.port}/health

ribbon:

ConnectTimeout: 50000

ReadTimeout: 50000

hystrix:

command:

default:

execution:

isolation:

thread:

timeoutInMilliseconds: 10000

server:

port: 8326

eureka:

client:

healthcheck:

enabled: true

service-url:

defaultZone: http://${registry.host:localhost}:${registry.port:8761}/eureka/

registry:

host: localhost

port: 31091

大致说下上述代码,main方法要使用@EnableSidecar注解,sidecar port代表监听Python运行的端口,server port代表Sidecar运行的端口,spring application name代表Sidecar的服务名,sidecar health-uri是Python健康接口,指向python的健康服务

服务调用 - consumer-server工程

调用方式一 : RestTemplate

ConsumerApplication.java

import org.springframework.boot.SpringApplication;

import org.springframework.cloud.client.SpringCloudApplication;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;

import org.springframework.context.annotation.Bean;

import org.springframework.web.client.RestTemplate;

@SpringCloudApplication

public class ConsumerApplication {

@Bean

@LoadBalanced

RestTemplate restTemplate() {

return new RestTemplate();

}

public static void main(String[] args) {

SpringApplication.run(ConsumerApplication.class, args);

}

}

application.yml

spring:

profiles:

active: "dev"

application:

name: consumer-server

server:

port: 8325

eureka:

client:

healthcheck:

enabled: true

service-url:

defaultZone: http://${registry.host:localhost}:${registry.port:8761}/eureka/

---

spring:

profiles: dev

registry:

host: localhost

port: 31091

RestTemplateController.java

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.client.RestTemplate;

@RestController

public class RestTemplateController {

@Autowired

private RestTemplate restTemplate;

@RequestMapping("/java-user")

public String JavaUser() {

return "{'username': 'java', 'password': 'java'}" ;

}

@RequestMapping("/python-user")

public String PythonUser() {

return restTemplate.getForEntity("http://sidecar-server/getUser", String.class).getBody();

// return restTemplate.getForEntity("http://localhost:3000/getUser", String.class).getBody();

}

}

这里做下说明,@LoadBalanced用于开启负载均衡,在这里有两种调用方式,使用和不使用@LoadBalanced

使用@LoadBalanced注解后,RestTemplate可以直接调用服务名

@Bean

@LoadBalanced

RestTemplate restTemplate() {

return new RestTemplate();

}

++++++++++++++++++++++++++++++

return restTemplate.getForEntity("http://sidecar-server/getUser", String.class).getBody();

不使用@LoadBalanced注解,RestTemplate调用的就是固定的IP+PORT

@Bean

// @LoadBalanced

RestTemplate restTemplate() {

return new RestTemplate();

}

++++++++++++++++++++++++++++++

return restTemplate.getForEntity("http://localhost:3000/getUser", String.class).getBody();

服务的启动顺序:Python服务,注册中心,sidecar-server工程,consumer-server工程

运行结果

调用方式二: Feign

SidecarController.java

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

import com.coisini.consumer.client.SidecarAPIClient;

@RestController

public class SidecarController {

private SidecarAPIClient sidecarAPIClient;

@Autowired

public SidecarController(SidecarAPIClient sidecarAPIClient) {

this.sidecarAPIClient = sidecarAPIClient;

}

@GetMapping("/getUser")

public Object getUser() {

return this.sidecarAPIClient.getUser();

}

}

SidecarAPIClient.java

import com.coisini.consumer.config.FeignConfigure;

import org.springframework.cloud.netflix.feign.FeignClient;

import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name="sidecar-server", configuration = FeignConfigure.class)

public interface SidecarAPIClient {

@GetMapping("/getUser")

Object getUser();

}

FeignConfigure.java

import feign.Logger;

import feign.codec.Encoder;

import feign.form.spring.SpringFormEncoder;

import org.springframework.beans.factory.ObjectFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.autoconfigure.web.HttpMessageConverters;

import org.springframework.cloud.netflix.feign.EnableFeignClients;

import org.springframework.cloud.netflix.feign.support.SpringEncoder;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

@EnableFeignClients(basePackages = "com.coisini")

public class FeignConfigure {

@Bean

Logger.Level feignLoggerLevel() {

return Logger.Level.FULL;

}

@Autowired

private ObjectFactory messageConverters;

@Bean

public Encoder feignFormEncoder() {

return new SpringFormEncoder(new SpringEncoder(messageConverters));

}

}

服务的启动顺序:Python服务,注册中心,sidecar-server工程,consumer-server工程

调用结果

至此,已完成微服务调用Python Web服务

Sidecar总结

Sidecar是一个用于监听非JVM应用程序(可以是Python或者Node或者Php等等)的一个工具,通过Sidecar可以实现Java和第三方应用程序的双向交互

第三方应用程序必须要实现一个接口,实时向Sidecar报告自己的状态,告诉Sidecar自己还在运行着。

Sidecar应用程序必须和第三方应用程序运行在同一台电脑上,也就是说他们之间是localhost,不能是IP访问

Demo下载

参考博客

end

springboot python整合_SpringCloud 整合 Python - Flask相关推荐

  1. python数据分析的主要流程-将Python和R整合进一个数据分析流程

    编译:丁一 黄念 丁雪 校对:席雄芬 姚佳灵 程序验证:郭姝妤 序言 在Python中调用R或在R中调用Python,为什么是"和"而不是"或"? 在互联网中, ...

  2. pythondjango项目集成_[Python]将Wagtail整合到Django2项目中

    Django是Python主流的Web框架之一,目前主要版本是Django 2.1,但是很多扩展都是基于Django 1.x.最近想做个简单的Web发布,选择了Wagtail,因为其他两个主流的cms ...

  3. python语言能够整合各类程序代码-python语言概述

    python语言的发展 python语言诞生于1990年,由Guide van Rossum设计并领导开发. python语言是开源项目的优秀代表,其解释器的全部代码都是开源的. 编写Hello程序 ...

  4. python r语言 数据分析_PythonR语言-将Python和R整合进一个数据分析流程

    命令行脚本 通过Windows 或Linux终端环境命令行运行R和Python脚本类似.要运行的命令被分解成以下部分: 参数说明 ▲ 是可执行的命令 (R代码中是 Rscript, Python代码中 ...

  5. 将Python和R整合进一个数据分析流程

             人工智能大数据与深度学习  公众号: weic2c 在Python中调用R或在R中调用Python,为什么是"和"而不是"或"? 在互联网中, ...

  6. python与数据分析结合_将Python和R整合进一个数据分析流程

    原标题:将Python和R整合进一个数据分析流程 在Python中调用R或在R中调用Python,为什么是"和"而不是"或"? 在互联网中,关于"R ...

  7. Python趣味代码整合之提升学生编程兴趣

    这篇文章主要是整合一些趣味代码,一方面自己对这些内容比较感兴趣,另一方面希望这些代码能提升学生的编程兴趣,其主旨是代码能在我的电脑上运行并有些趣味.         参考资料:             ...

  8. python视频网站项目_价值2400元的python全栈开发系列Flask Python Web 网站编程视频

    2 e/ b4 F1 c' H$ D! X 价值2400元的python全栈开发系列Flask Python Web 网站编程视频-优品课堂' z3 _1 Y7 ]6 j4 z # p# r# g* ...

  9. redis序列化_实例讲解Springboot以Template方式整合Redis及序列化问题

    1 简介 之前讲过如何通过Docker安装Redis,也讲了Springboot以Repository方式整合Redis,建议阅读后再看本文效果更佳: (1) Docker安装Redis并介绍漂亮的可 ...

最新文章

  1. 华为平板上wps另存为的文件在哪里能找到_原创干货 | WPS危害之嵌入ole对象绑定载荷...
  2. 详细介绍Oracle DBA工作职责
  3. ActiveMQ跑起来
  4. dubbo中log4j检查(开发环境中建议设置为false)
  5. flask web开发的相关博文学习
  6. Hemberg-lab单细胞转录组数据分析(二)
  7. 计算机国家实验教学示范中心,教育部、财政部关于批准2007年国家级实验教学示范中心建设单位的通知...
  8. axure树形表格_Axure教程:可增删改的树型结构
  9. 怎么禁用计算机usb驱动,在Windows中启用或禁用USB驱动器或端口的5种方法 | MOS86...
  10. Can‘t locate XXX/XXX.pm in @INC (you may need to install the XXX::XXX module)
  11. 大数据影响下的专题地图编制
  12. 视频教程-大数据技术-大数据
  13. Programming Rust Fast, Safe Systems Development(译) 表达式(第六章 完)
  14. php输出问号,所有特殊字符都是PHP / HTML中的问号
  15. 二、流水线的执行流程
  16. 计算机二级考试地点没有容量,2017年计算机二级office考试点积累
  17. Kotlin Contract(契约)
  18. Linux 设备树下的 platform 驱动示例
  19. Oracle建立表空间和用户
  20. 推荐信号与系统、信号处理书籍

热门文章

  1. IBM推新编码系统 实现高清视频技术大突破
  2. 人生最重要的十个健康伴侣
  3. 简单粗暴 我再送一波教程资料,Vue、大数据、AI都有
  4. 他初中学历做开发,3年在北京买了房,超过了99%的程序员!
  5. 佛系程序员:什么bug不bug的,随缘吧
  6. oracle group by sql,Oracle SQL GROUP BY“不是GROUP BY表达式”的帮助
  7. pcl完整分割聚类流程
  8. 第二期临床基因组家系数据分析实战,快速发表SCI文章
  9. 生信分析和统计绘图资源推荐!
  10. 「M1兼容」最新ps2022版photoshop 2022 Mac中文版下载安装教程分享