SpringCloud 融入 Python - Flask

前言

該篇文章分享如何將Python Web服務融入到Spring Cloud微服務體系中,並調用其服務,Python Web框架用的是Flaskjava

方案

Sidecar+ Flask,在這裏,咱們會使用SidecarPython接口註冊到SpringCloud中,將Python接口看成Java接口進行調用(經過SpringCloud去調用Sidecar,而後經過Sidecar去轉發咱們的程序請求)python

  • SidecarSpringCloud提供的一個可將第三方的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提供本身的健康狀態,getUserPython向外界提供的服務web

  • 運行方式
python manage.py runserver

sidecar工程

  • 添加依賴
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-netflix-sidecar</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
  • 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-uriPython健康接口,指向python的健康服務

spring

服務調用 - DemoServer工程(端口8325)

調用方式一 : RestTemplate

  • DemoServerApplication.java
@SpringBootApplication
public class DemoServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoServerApplication.class, args);
    }
    
    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
  • 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://demo-sidecar/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://demo-sidecar/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工程,DemoServer工程
  • 運行結果
    在這裏插入圖片描述
    在這裏插入圖片描述

調用方式二: Feign

  • congfig類中需添加註解@EnableFeignClients,具體使用請百度
  • SidecarController.java
@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
@FeignClient(name="demo-sidecar", 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.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfigure {
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;
   
    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }
}
  • 服務的啓動順序:Python服務,註冊中心,sidecar工程,DemoServer工程
  • 調用結果
    在這裏插入圖片描述在這裏插入圖片描述
    至此,已完成微服務調用Python Web服務

Sidecar總結

  • Sidecar是一個用於監聽非JVM應用程序(能夠是Python或者Node或者Php等等)的一個工具,經過Sidecar能夠實現Java和第三方應用程序的雙向交互
  • 第三方應用程序必需要實現一個接口,實時向Sidecar報告本身的狀態,告訴Sidecar本身還在運行着。
  • Sidecar應用程序必須和第三方應用程序運行在同一臺電腦上,也就是說他們之間是localhost,不能是IP訪問

參考博客

SpringCloud 整合Python 感謝大佬json

endflask

相關文章
相關標籤/搜索