springboot python整合_SpringCloud 整合 Python - Flask
前言
該篇文章分享如何將Python Web服務(wù)融入到Spring Cloud微服務(wù)體系中,并調(diào)用其服務(wù),Python Web框架用的是Flask
方案
Sidecar+ Flask,在這里,我們會(huì)使用Sidecar將Python接口注冊(cè)到SpringCloud中,將Python接口當(dāng)作Java接口進(jìn)行調(diào)用(通過(guò)SpringCloud去調(diào)用Sidecar,然后通過(guò)Sidecar去轉(zhuǎn)發(fā)我們的程序請(qǐng)求)
Sidecar是SpringCloud提供的一個(gè)可將第三方的rest接口集成到SpringCloud中的工具
Python服務(wù)
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)
大致說(shuō)下上述代碼,Python服務(wù)監(jiān)聽(tīng)3000端口,health方法用于給Sidecar提供健康接口,用于實(shí)時(shí)向Sidecar提供自己的健康狀態(tài),getUser是Python向外界提供的服務(wù)
運(yùn)行方式
python manage.py runserver
sidecar-server工程
添加依賴(lài)
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
大致說(shuō)下上述代碼,main方法要使用@EnableSidecar注解,sidecar port代表監(jiān)聽(tīng)Python運(yùn)行的端口,server port代表Sidecar運(yùn)行的端口,spring application name代表Sidecar的服務(wù)名,sidecar health-uri是Python健康接口,指向python的健康服務(wù)
服務(wù)調(diào)用 - consumer-server工程
調(diào)用方式一 : 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();
}
}
這里做下說(shuō)明,@LoadBalanced用于開(kāi)啟負(fù)載均衡,在這里有兩種調(diào)用方式,使用和不使用@LoadBalanced
使用@LoadBalanced注解后,RestTemplate可以直接調(diào)用服務(wù)名
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
++++++++++++++++++++++++++++++
return restTemplate.getForEntity("http://sidecar-server/getUser", String.class).getBody();
不使用@LoadBalanced注解,RestTemplate調(diào)用的就是固定的IP+PORT
@Bean
// @LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
++++++++++++++++++++++++++++++
return restTemplate.getForEntity("http://localhost:3000/getUser", String.class).getBody();
服務(wù)的啟動(dòng)順序:Python服務(wù),注冊(cè)中心,sidecar-server工程,consumer-server工程
運(yùn)行結(jié)果
調(diào)用方式二: 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));
}
}
服務(wù)的啟動(dòng)順序:Python服務(wù),注冊(cè)中心,sidecar-server工程,consumer-server工程
調(diào)用結(jié)果
至此,已完成微服務(wù)調(diào)用Python Web服務(wù)
Sidecar總結(jié)
Sidecar是一個(gè)用于監(jiān)聽(tīng)非JVM應(yīng)用程序(可以是Python或者Node或者Php等等)的一個(gè)工具,通過(guò)Sidecar可以實(shí)現(xiàn)Java和第三方應(yīng)用程序的雙向交互
第三方應(yīng)用程序必須要實(shí)現(xiàn)一個(gè)接口,實(shí)時(shí)向Sidecar報(bào)告自己的狀態(tài),告訴Sidecar自己還在運(yùn)行著。
Sidecar應(yīng)用程序必須和第三方應(yīng)用程序運(yùn)行在同一臺(tái)電腦上,也就是說(shuō)他們之間是localhost,不能是IP訪問(wèn)
Demo下載
參考博客
end
總結(jié)
以上是生活随笔為你收集整理的springboot python整合_SpringCloud 整合 Python - Flask的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 编程方法学23:搜索排序与算法效率分析
- 下一篇: 编程方法学24:管理大型数据中的良好软件