问题:
遇到两个服务器需要数据同步 而同步时候比较浪费时间 ,如果按以前的方式 等同步完毕以后在执行下面数据会导致效率极慢
采用了异步调引方式
1.首先想到的是 httpclient 调用异步
具体参考
HttpClient详细使用示例
2.研究发现太复杂了 ,想了想自己使用的springboot,而异步调用这个是很常见的问题,于是发现@Async方式
具体参考
使用SpringBoot的@Async实现异步调用方法,以及自己开启新线程异步调用
3.遇到的问题 :
1:问题
开始数据同步方法写到一个公用的controller 里面让其他controller 调用 当设定@Async注解时候 发现其他service里调用此方法没有效果
2.解决方式:
仔细研究发现@Async必须写到service层才可以生效
3.问题
调用 @autoword serviceImpl 实现类 没有成功
4.解决方式:
必须调用service 类 因为impl是动态生成的 不具有调用行
最后结果`
service
public interface SyncService {
void dataLink(Object mapLink, String url);
}
serviceImpl
@Service
public class SyncServiceImpl implements SyncService {
@Override
@Async
public void dataLink(Object mapLink, String url) {
Map<String, Object> map = new HashMap<>();
map.put("loginAccount", Constant.loginAccount);
map.put("accountPassword", Constant.accountPassword);
String res = HttpUtil.sendPost(urlLogin, map, null);
JSONObject resObj = JSONObject.parseObject(res);
System.out.println(resObj.getJSONObject("data").getString("token"));
Map<String, Object> map2 = new HashMap<>();
String jsonObject = JSONObject.toJSONString(mapLink, SerializerFeature.WriteNullStringAsEmpty);
map2.put("copyrightObj", jsonObject);
System.out.println(jsonObject);
String res2 = HttpUtil.sendPost(url, map2, resObj.getJSONObject("data").getString("token"));
System.out.println(url + "------------------" + res2);
}
}
需要调用的service 加
@Autowired
SyncService syncService;
调用方法
syncService.dataLink(copyrightDetailPrdArticleInfo, Constant.journal);