场景描述:
现有项目A和项目B,因业务需要,要同步两个项目之间的一些数据。
项目A的一些信息要推送给项目B:推送方法
String company = "xxxx公司";
String name = "xxxx";
Map<String,String> map = new HashMap<String, String>();
map.put("companyName", company);
map.put("drawee", name);
String returnJson = HttpRequest.send("http://xxx.xxx.x.xxx:8080" + "/xxxxxx/xxxx",
JSON.parse(JsonUtil.map2Json(map)), "UTF-8");
JSONObject o = JSONObject.parseObject(returnJson);
Map m = (Map) o.get("body");
code = o.getString("errorCode");
推送工具类:
public static String send(String url, Object jsonObject,String encoding) throws ParseException, IOException{
String body = "";
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
//装填参数
StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
//设置参数到请求对象中
httpPost.setEntity(s);
// System.out.println("请求参数:"+nvps.toString());
//设置header信息
//指定报文头【Content-type】、【User-Agent】
// httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
return body;
}
项目B被调取方法以及返回结果:
@PostMapping("/updatePic")
public AjaxResult updatePic(@RequestBody JSONObject maps,HttpServletRequest request, HttpServletResponse response) {
System.out.println("---------sendPara-----"+request.getParameter("sendPara"));
// Map maps = JsonUtil.json2Map(request.getParameter("sendPara"));
Map map= MapUtils.nullToEmpty(maps);
System.out.println("---------appointmentnum-----"+map.get("appointmentnum").toString());
System.out.println("---------unloadPic-----"+map.get("unloadPic").toString());
System.out.println("---------ton-----"+map.get("ton").toString());
String appointmentNum = map.get("appointmentnum").toString();
String unloadPic = map.get("unloadPic").toString();
String ton = map.get("ton").toString();
Double t = Double.parseDouble(ton);
if (StringUtils.isNotBlank(appointmentNum)) {
BookingSales sales = bookingSalesService.selectByAppointmentNum(appointmentNum);
int a = 0;
if (sales != null) {
Double ton2=Double.parseDouble(ton);
sales.setUnloadPic(unloadPic);
sales.setTon(ton2);
sales.setAmount(DoubleUtil.mul(t,(sales.getPrice()==null)?0:sales.getPrice()));
sales.setUpdateTime(new Date());
a = bookingSalesService.updateByPrimaryKeySelective(sales);
}
if (a > 0) {
return success();
} else {
return error();
}
} else {
logger.info(CodeMessage.Msg_103);
return error(CodeMessage.Msg_103);
}
}
但这样跨系统交互之后,原项目的事务就失效了,项目和业务要求必须同步的情况下,就要在双方加入消息队列或者重新写一套对应的事务管理了,要求不高的话就这样写即可。
如有不足,望高手指教探讨。