1.访问请求token
//获取token接口
public Map<String, String> whmallToken() {
Map<String, String> map = new HashMap<>();
//rowBody基理提供参数
String rowBody = "{\"app_id\": \"xxx\",\"app_secret\": \"xxx\"}";
String company = "xxxToken";
String url = "https://xxx.xxx.com/token/v1";
try {
//调用接口获取token文本
String tokenContent = sendRollbackInfo(rowBody, company,null,url);
//获取content层内容
JSONObject json = JSONObject.parseObject(tokenContent);
String content = json.getString("data");
//获取token和过期时间存入map
JSONObject jsons = JSONObject.parseObject(content);
String token = jsons.getString("token");
String expiresTime = jsons.getString("expire");
map.put("token", token);
map.put("expiresTime", expiresTime);
} catch (Exception ex) {
String error = "解析json异常";
map.put("error", error);
}
return map;
}
2.访问发送工具类:
public String sendRollbackInfo(String urlInfo, String company, String downUrl, String url) {
String result = "";
PrintWriter out = null;
BufferedReader in = null;
try {
String parm = "";
String sign = "";
URL realUrl = null;
HttpURLConnection conn = null;
switch (company) {
case "birdotech":
String urlInfos = "dc_" + urlInfo + "_dc";
sign = shaEncode1(urlInfos).toUpperCase();
realUrl = new URL(url);
conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestProperty("Content-Type", "application/json-patch+json");
conn.addRequestProperty("sign", sign);
conn.addRequestProperty("fromOperatorMan", "text特殊密钥");
conn.addRequestProperty("opSystem", "text特殊密钥");
break;
case "scilligence":
realUrl = new URL(url);
conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.addRequestProperty("X-Requested-With", "XMLHttpRequest");
conn.addRequestProperty("Authorization", "text特殊密钥" + rdsKey);
urlInfo = "Vendorhashcode=" + vendorHashCode + "&Data=" + downUrl;
break;
case "szdieckmann":
realUrl = new URL(url);
conn = (HttpURLConnection) realUrl.openConnection();
urlInfo = "downurl=" + downUrl;
break;
case "whmall":
//检测redis是否有token密钥 没有添加进去
if (!redisProductUtil.exitsKey("whmallToken")) {
redisProductUtil.setCacheWithCustomerTime("whmallToken", whmallToken().get("token"), Long.parseLong(whmallToken().get("expiresTime")) / 60);
}
realUrl = new URL(url);
conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.addRequestProperty("Auth-Token", redisProductUtil.get("whmallToken"));
JSONObject jsonObject = new JSONObject();
jsonObject.put("stock_file_download_url", downUrl);
urlInfo = String.valueOf(jsonObject);
break;
case "whmallToken":
realUrl = new URL(url);
conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
break;
case "pharmablock":
realUrl = new URL(url);
conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.addRequestProperty("Authorization","Basic "+phaToken());
urlInfo ="{}";
break;
case "chemsnet":
realUrl = new URL(url);
conn = (HttpURLConnection) realUrl.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.addRequestProperty("appKey","text特殊密钥");
conn.addRequestProperty("appSecret","text特殊密钥");
break;
}
conn.setRequestMethod("POST");
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.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(urlInfo);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return result;
}
3.线程一 生成文件
package leyan.admin.multclass;
import com.alibaba.fastjson.JSON;
import leyan.admin.entity.product.*;
import leyan.admin.service.AdminAuthService;
import leyan.admin.service.CallbackAddressService;
import leyan.admin.service.InterfaceUserService;
import leyan.admin.service.ProductService;
import leyan.admin.util.*;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@Service
@RequiredArgsConstructor
@RestController
@Setter
@Getter
public class StockSendUrl extends Thread{
private final ProductService productService;
private final AdminAuthService adminAuthService;
private final CallbackAddressService callbackAddressService;
private final InterfaceUserService interfaceUserService;
private final DockingUtil dockingUtil;
private final DockingStatusUtil dockingStatusUtil;
private final RedisProductUtil redisProductUtil;
private String username;
public void setUsername(String username)
{
this.username = username;
}
private String password;
public void setPassword(String password)
{
this.password = password;
}
@Value("${system.upload.log.stockprice.path}")
private String stockLogFile;
@Value("${leyan.stock.file.path}")
private String root;
@Value("${leyan.stock.file.url}")
private String url;
private final String prefix = "LeyanStock";
//文件是否存在
public void run(){
var user = interfaceUserService.login(username, password);
//写入txt所需的所有数据
Lock lock = new ReentrantLock();
try {
//多个请求同时访问的时候枷锁,当天只生成一次
lock.lock();
//先刪除在創建文件
String filePath = "";
filePath = KeyCustomerUtil.createFile(root, prefix, user);
List<KeyCustomerQueryProductPackage> allProductPackage = user.getIsAll() == 0 ? productService.getAllProductPackage(user) : productService.getNoStockProduct(user);
//测试数据截取100
//allProductPackage = allProductPackage.stream().limit(20).collect(Collectors.toList());
BufferedWriter bw = new BufferedWriter(new FileWriter(filePath, true));
bw.write(JSON.toJSONString(allProductPackage));
bw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();//释放资源
}
}
}
- 线程二 发送文件地址
package leyan.admin.multclass;
import com.alibaba.fastjson.JSONObject;
import leyan.admin.entity.InterfaceUser;
import leyan.admin.service.CallbackAddressService;
import leyan.admin.service.InterfaceUserService;
import leyan.admin.service.ProductService;
import leyan.admin.util.DockingUtil;
import leyan.admin.util.FileUtil;
import leyan.admin.util.KeyCustomerUtil;
import leyan.admin.util.StrUtil;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@RequiredArgsConstructor
@RestController
@Setter
@Getter
public class StockTextMade extends Thread{
private final InterfaceUserService interfaceUserService;
private final ProductService productService;
private final CallbackAddressService callbackAddressService;
private final DockingUtil dockingUtil;
@Value("${system.upload.log.stockprice.path}")
private String stockLogFile;
@Value("${leyan.stock.file.path}")
private String root;
@Value("${leyan.stock.file.url}")
private String url;
private final String prefix = "LeyanStock";
//文件是否存在
private boolean exists = false;
private String username;
public void setUsername(String username)
{
this.username = username;
}
private String password;
public void setPassword(String password)
{
this.password = password;
}
//run线程不带返回值 callable携带返回值
public Map Callable(){
Map map = new HashMap();
var user = interfaceUserService.login(username, password);
JSONObject jsonObject = new JSONObject();
if (checkIsFile(user)) {
jsonObject.put("downurl", KeyCustomerUtil.getMesFilePath(url, root, prefix, user));
String downUrl = KeyCustomerUtil.getMesFilePath(url, root, prefix, user);
map = sendRollbackUrl(username, String.valueOf(jsonObject), downUrl);
}else {
map.put("type", "wait");
map.put("description", "文件生成中");
}
return map;
}
private boolean checkIsFile(InterfaceUser user) {
exists = false;
File file = new File(root);
if (!file.exists()) {
file.mkdir();
}
File[] files = file.listFiles();
Float discount = user.getDiscount();
String strDiscount = discount >= 1 ? "1" : StringUtils.substringAfterLast(String.valueOf(discount), ".");
String strIsAll = user.getIsAll() == 0 ? "no" : "all";
String isCas = user.getIsCas() == 1 ? "cas" : "nocas";
String isEnglish = user.getIsEnglish() == 1 ? "english" : "noenglish";
String isIntpart = user.getIsIntpart() == 1 ? "intpart" : "nointpart";
for (int i = 0; i < files.length; i++) {
if (files[i].getName().contains(strDiscount + "-" + strIsAll + "-" + isCas + "-" + isEnglish + "-" + isIntpart + "-" + LocalDate.now().toString())) {
exists = true;
break;
}
}
return exists;
}
private HashMap<String, String> sendRollbackUrl(String username, String filePath, String downUrl) {
HashMap<String, String> map = new HashMap();
List<String> verificationUserName = productService.getUserName();
if (verificationUserName.contains(username)) {
String addressUrl = callbackAddressService.getAddressByUsername(username);
String result = dockingUtil.sendRollbackInfo(filePath, username, downUrl, addressUrl);
if (StringUtils.isNotBlank(result)) {
map.put("type", "success");
map.put("description", "地址已发送成功");
map.put("返回信息", result);
} else {
map.put("type", "error");
map.put("description", "地址发送失败");
}
return map;
} else {
String url1 = callbackAddressService.getAddressByUsername(username);
String result = "";
PrintWriter out = null;
BufferedReader in = null;
URL url = null;
try {
url = new URL(url1);
URLConnection connect = url.openConnection();
connect.setRequestProperty("content-type", "application/x-www-form-urlencoded;charset=utf-8");
connect.setRequestProperty("method", "POST");
connect.setDoOutput(true);
connect.setDoInput(true);
out = new PrintWriter(connect.getOutputStream());
// 发送请求参数
//out.print("datas=" + json);
out.print("downurl=" + filePath);
out.flush();
//数据交互返回值200/400/500...
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url1);
CloseableHttpResponse response = null;
StringEntity entitys = new StringEntity(filePath);
post.setEntity(entitys);
response = httpClient.execute(post);
//System.out.println(response.getStatusLine().getStatusCode());
// 定义BufferedReader输入流来读取URL的响应
if (response != null && response.getStatusLine().getStatusCode() == 200) {
in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String line = "";
while ((line = in.readLine()) != null) {
result += line;
if (StringUtils.isNotBlank(result)) {
map.put("type", "success");
map.put("description", "地址已发送成功");
}
}
} else {
map.put("type", "error");
map.put("description", "数据交互出错,请检查平台服务是否开启?出错原因报:");
}
} catch (IOException e) {
map.put("type", "success");
map.put("description", "地址已发送成功");
} catch (Exception e) {
map.put("type", "error");
map.put("description", "数据对接失败,接收地址异常:");
e.printStackTrace();
} finally {
FileUtil.readWriteFile(stockLogFile, StrUtil.getDate() + "数据交互出错,请检查平台服务是否开启?出错原因报:");
}
return map;
}
}
}
5.调用线程
if (!checkIsFile(user)) {
stockSendUrl.setUsername(username);//生成文件
stockSendUrl.setPassword(password);//生成文件
stockSendUrl.start();//开启线程
}
stockTextMade.setUsername(username);//发送地址
stockTextMade.setPassword(password);//发送地址
Thread.sleep(2000);//睡眠 在不睡眠得情况下可以调整线程优先级进行处理
return stockTextMade.Callable();//返回callable信息