python接入spring cloud_SpringCloud 整合 Python - Flask

前言

该篇文章分享如何将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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在这个互联网时代,客服可以说必不可少,每个电商网站都应该有一个强大的智能客服对话系统,以满足用户沟通的需求。智能客服对话系统,不仅需要人工的沟通,同时结合人工智能实现智能对话,减少人工客服的成本,势在必行。基于SpringBoot+Python的多语言前后端智能多人聊天系统课程,将以基础知识为根基,带大家完成一个强大的智能客服系统,该系统将包含以下功能:智能对话机器人、单聊、群聊、消息撤回、上线、下线通知、用户动态信息实时提示等。即时通讯和人工智能,在未来的发展趋势,必然需要大批人才,掌握这两个技术势在必行。项目是一个真实可用的项目,商业价值不言而喻。也可以基于课程的基础上进一步完善和优化,所以价值是很高的。本课程包含的技术: 开发工具为:IDEA、WebStorm、PyCharmTensorflowRNNLSTMAnacondaSpringBoot SpringCloudWebsocketSTOMPDjangoVue+Nodejs+jQuery等 课程亮点: 1.与企业接轨、真实工业界产品2.从基础到案例,逐层深入,学完即用3.市场主流的前后端分离架构和人工智能应用结合开发4.多语言结合开发,满足多元化的需求5.涵盖TensorFlow1.x+TensorFlow2.x版本6.智能机器人实战7.即时通讯实战8.多Python环境切换9.微服务SpringBoot10.集成SpringCloud实现统一整合方案 11.全程代码实操,提供全部代码和资料 12.提供答疑和提供企业技术方案咨询 课程目录:第一章、Anaconda以及TensorFlow环境和使用0、智能多人聊天系统课程说明1、智能多人聊天系统之Anaconda讲解2、智能多人聊天系统之Anaconda安装和使用3、智能多人聊天系统之Anaconda之conda命令使用4、智能多人聊天系统之TensorFlow讲解5、智能多人聊天系统之TensorFlow安装和使用6、TensorFlow常量、变量和占位符实战讲解17、TensorFlow常量、变量和占位符实战讲解28、TensorFlow原理补充讲解9、TensorFlow四则运算实战讲10、TensorFlow矩阵操作以及运算实战讲解111、TensorFlow矩阵操作以及运算实战讲解212、TensorFlow均匀分布和正态分布数据实战讲解13、智能多人聊天系统之Numpy实战讲解14、智能多人聊天系统之matplotlib实战讲解15、TensorFlow深度学习DNN讲解16、TensorFlow常用Python扩展包讲解17、TensorFlow常用回归算法以及正则化讲解18、TensorFlow损失函数定义和使用实战讲解19、TensorFlow优化器讲解以及综合案例实战讲解20、智能多人聊天系统之RNN讲解21、智能多人聊天系统之RNN种类讲解22、智能多人聊天系统之RNN代码实战23、智能多人聊天系统之LSTM讲解24、智能多人聊天系统之attention机制讲解25、智能多人聊天系统之Django环境构建及初体验26、智能多人聊天系统之Django开发27、Python章节环境侯建和项目搭建28、Python TensorFlow读取训练数据代码编写29、Python TensorFlow形成语料编码30、Python TensorFlow保存字典文件31、Python TensorFlow构建词向量32、Python TensorFlow构建lstm模型以及attention wrapper33、Python TensorFlow训练代码编写34、Python整体代码讲解35、Python运用模型代码讲解36、SpringBoot讲解以及构建web应用37、Spring Cloud注册中心构建38、智能多人聊天系统之前端Vue项目构建39、SpringBoot+Websocket群聊40、SpringBoot+Websocket昵称群聊41、SpringBoot+Websocket群聊+单聊实战42、SpringBoot+Stomp单聊143、SpringBoot+Stomp单聊244、SpringBoot+Stomp单聊+群聊45、Django Web整合TF代码讲解及Postman调试46、智能客服系统单聊群聊等项目功能代码讲解147、智能客服系统单聊群聊等项目功能代码讲解248、智能客服系统集成机器人对话代码开发讲解49、智能机器人TensorFlow2版本升级实战之训练模型代码讲解50、智能机器人TensorFlow2版本升级实战之预测代码讲解 51、智能机器人TensorFlow2版本升级实战补充讲解
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值