1、需求说明
有两个springBoot项目:
项目A将数据读到HashMap内存中并提供restFul接口供其他程序调用获取map数据;
项目B则负责先读取A中的map数据,再做其他逻辑操作;
下面则只介绍项目B的具体实现;
2、测试代码
使用springBoot自带的RestTemplate,来远程调用restFul接口并返回json数据;
(1)restFul接口存在的测试数据
(2)代码测试
import com.gl.wnmodel.util.MapJsonUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
public class test {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("id","123456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> formEntity = new HttpEntity<MultiValueMap<String, String>>(map,headers);
System.out.println("远程调用传递参数:" + formEntity);
String result = restTemplate.postForEntity("http://127.0.0.1:8099/getMap", formEntity, String.class).getBody();
System.out.println("远程调用返回结果:" + result);
}
}
(3)返回结果
远程调用传递参数:<{id=[123456]},{Content-Type=[application/x-www-form-urlencoded]}>
...
远程调用返回结果:{"18838517357":"20200407","16678924563":"20200414","18838517356":"20200406"}
3、封装成方法并返回map
import com.gl.wnmodel.util.MapJsonUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
public class GetRemoteData {
public static final GetRemoteData instance = new GetRemoteData();
public Map<String,Object> getRemoteMap(String url){
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
//map.add("id","123456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> formEntity = new HttpEntity<MultiValueMap<String, String>>(map,headers);
String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
//将json映射为Map
Map<String, Object> mapData = MapJsonUtil.jsonToMap(result);
System.out.println("远程调用返回结果大小:" + mapData.size());
return mapData;
}
}
public static Map<String,Object> jsonToMap(String jsonStr){
try {
Map<String,Object> map2= JSON.parseObject(jsonStr, HashMap.class);
return map2;
}catch (Exception ex){
throw new RuntimeException("json转map出错",ex);
}
}