#最近在写Hadoop集群推荐系统,后台实用的是SpringBoot,然鹅后台的数据分析核心的算法部分是和SpringBoot分离的
需要远程调用
Python使用的是django,Java是Springboot,Python调Java可以使用Telnet调用Java的dubbo接口(会另写一篇),Java调用Python就是用Spring提供的RestTemplate
需求:SpringBoot远程调用python的函数
实现:SpringBoot---RestTemplate+python rest接口
首先配置RestTemplate
package com.hqjl.career.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
@Component
public class RestTemplateConfig {
@Bean
@ConditionalOnMissingBean({RestOperations.class , RestTemplate.class})
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
List> messageConverters = restTemplate.getMessageConverters();
Iterator> iterator = messageConverters.iterator();
while (iterator.hasNext()) {
HttpMessageConverter> converter = iterator.next();
if(converter instanceof StringHttpMessageConverter) {
iterator.remove();
}
}
messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
return restTemplate;
}
@Bean
@ConditionalOnMissingBean({ClientHttpRequestFactory.class})
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(15000);
factory.setConnectTimeout(12000);
return factory;
}
}
我们这里是远程调用rest,post方法需要带参数
首先设置请求头
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
参数
JSONObject param = new JSONObject();
param.put("gradeID",gradeID);
param.put("schoolID" , schoolID);
param.put("type" , 1);
定义URL,这里我有部分URL是在配置文件中的,不同环境ip,port可能会变动
@Value("${pythonserv}")
private String pyURL;
String URL = pyURL + "/intention/commonList";
请求以及响应接收
HttpEntityentity = new HttpEntity<>(param.toString() , httpHeaders);
HttpEntityresponse = restTemplate.exchange(URL, HttpMethod.POST , entity , String.class);
简单说一下Python端,因为有几个坑,首先Python端接收到参数解析完类型是unicode,我们取参数肯定想用的是字典类型嘛,
所以我简单写一下,有兴趣的童鞋可以试一下每一步打印type()
def commonList(request):
dict = json.loads(request.body.decode()) unicode
dict = dict.encode('utf-8') str
dict = json.loads(dict) dict
都看到这了,点个赞再走呗