在java中调用flask部署tensorflow的http服务

利用flask快速部署tensorflow的http服务:

两个地方需要注意:

  1. 在@app.route('/hello', methods=['GET','POST'])一定要写好方法method,不然在java方面会报405错误
  2. 我在网上找到的wsgi,但我的电脑不知道为什么无法开启这个服务,因此我尝试了一下直接用app.run()也可以
import os
from gevent import monkey
monkey.patch_all()
from flask import Flask, request
from gevent import pywsgi as wsgi
import tensorflow as tf

os.environ["CUDA_VISIBLE_DEVICES"] = "" #不使用GPU
a = tf.placeholder(tf.int32, shape=(), name="input")
asquare = tf.multiply(a, a, name="output")
sess = tf.Session()  # 创建tensorflow session,也可以在这里载入tensorflow模型

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello World'

@app.route('/hello', methods=['GET','POST'])
def response_request():
    num = request.args.get('num')
    for i in range (100):
        ret = sess.run([asquare], feed_dict={a: num})  #运行tensorflow模型
    return str(ret)

if __name__ == "__main__":
    # server = wsgi.WSGIServer(('127.0.0.1', 19877), app)
    # server.serve_forever()
    app.run(host="127.0.0.1", port=8888, threaded=True)

java调用http接口:

package book.dao;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Author: Yang JianQiu
 * @Date: 2019/4/26 11:34
 * jdk类HttpURLConnection调用第三方http接口
 *
 * 通常分get和post两种方式
 *
 * 参考资料:
 * http://www.cnblogs.com/angusbao/p/7727649.html
 */

public class test {

	    /**
	     * 以post或get方式调用对方接口方法,
	     * @param pathUrl
	     */
	    public static void doPostOrGet(String pathUrl, String data){
	        OutputStreamWriter out = null;
	        BufferedReader br = null;
	        String result = "";
	        try {
	            URL url = new URL(pathUrl);
	            //打开和url之间的连接
	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	            //请求方式
	            conn.setRequestMethod("POST");
	            //conn.setRequestMethod("GET");

	            //设置通用的请求属性
	            conn.setRequestProperty("accept", "*/*");
	            conn.setRequestProperty("connection", "Keep-Alive");
	            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
	            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

	            //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
	            conn.setDoOutput(true);
	            conn.setDoInput(true);

	            /**
	             * 下面的三句代码,就是调用第三方http接口
	             */
	            //获取URLConnection对象对应的输出流
	            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
	            //发送请求参数即数据
	            out.write(data);
	            //flush输出流的缓冲
	            out.flush();

	            /**
	             * 下面的代码相当于,获取调用第三方http接口后返回的结果
	             */
	            //获取URLConnection对象对应的输入流
	            InputStream is = conn.getInputStream();
	            //构造一个字符流缓存
	            br = new BufferedReader(new InputStreamReader(is));
	            String str = "";
	            while ((str = br.readLine()) != null){
	                result += str;
	            }
	            System.out.println(result);
	            //关闭流
	            is.close();
	            //断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
	            conn.disconnect();

	        } catch (Exception e) {
	            e.printStackTrace();
	        }finally {
	            try {
	                if (out != null){
	                    out.close();
	                }
	                if (br != null){
	                    br.close();
	                }
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }

	    public static void main(String[] args) {
	        doPostOrGet("http://127.0.0.1:8888/hello?num=10", "");
	    }
}

参考资料:

  1. 报405错误:https://blog.csdn.net/miao0967020148/article/details/80278094?utm_source=blogxgwz1
  2. java代码:https://www.cnblogs.com/swordfall/p/10757499.html#auto_id_1
  3. flask快速搭建tensorflow http服务:https://blog.csdn.net/wangjian1204/article/details/76732337
  4. 机器学习模型应用到javaweb:https://www.zhihu.com/question/344630570/answer/814940615

你可能感兴趣的:(Python学习,懒得分类)